How do I read/understand the following statement in Java?
Class<?>[] groups() default {};
Class < ? extends Payload>[] payload() default {};
I think I can understand them individually but I don't know if I get good sense of what it means in its entirety.
Individually:
Class<?>
means any class and Class< ? extends Payload>
means any class that extends the Payload
class[ ]
seems to refer to any array of classes. Is that correct?groups()
and payload()
are method names.default{}
Use this when there is no implementation? I am really not sure how to understand the above statements? Any help would be very much appreciated.
The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign ( @ ) (@ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.
@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }
An annotation is a construct associated with Java source code elements such as classes, methods, and variables. Annotations provide information to a program at compile time or at runtime based on which the program can take further action.
default {} --> Use this when there is no implementation?
In an Annotation definition you can specify a default value for a parameter. The {}
after default is an array literal for an empty array. You could also set it to some non empty value. This also works for other objects too. eg the Data
annotation from lombok where a default string is declared:
public @interface Data {
String staticConstructor() default "";
}
Class means any class and "Class< ? extends Payload>" means any class that extends the Payload class
Yes
[ ] --> Seems to refer to any array of classes. Is that correct?
Yes
groups() and payload() are method names.
They are the name of the parameter used in annotation declaration, as well as the name of the getter methods for those values. eg you could define:
@Data(staticConstructor = "of") class Foobar {}
And later you could get the value by using the getter method created:
Data dataAnnotation = Foobar.class.getAnnotation(Data.class);
String staticConstructor = dataAnnotation.staticConstructor();
Note that you will not actually be able to retrieve the value for an annotation in runtime unless the annotation definition is also annotated with @Retention(RetentionPolicy.RUNTIME)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With