Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic annotation of arrays in Java

I find this snippet of code in twitter, it is hard to me to understand what happens here, all I can see that the OP of this code is creating an annotation, I can see also that the OP use array of arrays in this code, and also use generics :

class Woww {
    @Wow Wow @Wow [] @Wow [] wow(@Wow Wow[] wow@Wow[])@Wow[]@Wow[] {
        return new Wow@Wow[]@Wow[]@Wow[]@Wow[]{
            {wow}
        };
    }
}

@Target({ElementType.TYPE_USE})
@interface Wow {
}

Can you please explain to me what happens exactly in this code, and how we can use it in a simple example, Thanks

like image 998
Walid Haridi Avatar asked Jan 16 '20 21:01

Walid Haridi


1 Answers

There are two tricks at play here:

Type Use Annotation Instances

First, since Java 8 the use of a type can be annotated with an annotation, and this includes individual array dimensions. From the Java Language Specification, 10.1:

Each bracket pair in an array type may be annotated by type annotations (§9.7.4). An annotation applies to the bracket pair (or ellipsis, in a variable arity parameter declaration) that follows it.

Placement of Array Dimensions

Second, according to the Java Syntax array dimensions for the return type can be placed both with the return type and after the list of parameters, and similarly for individual variables.

Example

This means that code like this (the method's parameter declaration):

@Wow Wow[] wow@Wow[]

is the same as:

@Wow Wow[]@Wow[] wow

once the square brackets are grouped with the element type, where the array type and inner dimensions are annotated with @Wow.

like image 97
SDJ Avatar answered Oct 04 '22 23:10

SDJ