When we create a custom annotation, we declare elements as methods and later set values as if they were attributes.
For example, here we have declared a custom annotation ComponentType
with elements name()
and description()
that look like methods.
public @interface ComponentType {
String name();// declared as method
String description();
}
When the annotation is used, they look like the below:
@ComponentType(name = "userContainer", // value looks like an attribute
description = "a user container")
public class UserEntity { }
My question is : Why doesn't Java allow to declaring elements as attributes, like this?
public @interface ComponentType {
String name; // Compilation Error
String description;
}
If the properties of an annotation weren't defined as abstract methods in an interface, they would have been members. Something like:
public @interface ComponentType {
String name;
String description;
}
However, all the members in an interface are implicitly final
(and static
) and the above code does not compile, because name
and description
aren't initialized.
But if they were actually initialized with some values:
public @interface ComponentType {
String name = "name";
String description = "description";
}
then snippets like the following one wouldn't have been possible:
@ComponentType(
name = "userContainer" //cannot assign a value to a final variable
, description = "a user container")
My observation is:
Java consider annotations as special type of interface so:
Like interface we can declare only final attributes in an annotation:
String appName = "test application";//final attribute, never reset value
Annotation may contains only abstract methods(a method that is declared without an implementation).
public @interface ComponentType { String name();// declared as abstract method
When we annotated elements(eg class, method, attribute) by annotation we need to set return value of those abstract methods, which looks like attribute but actually acts as an implementation.
@ComponentType(name = "userContainer"//set return value of method name()
We can use the values we set during annotated elements(eg class, method, attribute) by simply calling abstract methods of annotation.
Annotation annotation = annotatedClassObject.getAnnotation(ComponentType.class); ComponentType componentType = (ComponentType) annotation; String someName = componentType.name(); //returns value set during annotating
So like as interface ,
Expecting More Feedback / Answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.