'Default properties of Java Annotation
What are the exact default values of two meta annotations (Target and Retention) in a user defined annotation?
public @interface AnnotationWithDefaultProps {
}
Solution 1:[1]
According to the source code, none of them has a default value, which means you must provide it, whenever you use the annotation. The meaning of the missing annotation is defined in the javadoc:
For Target
it means
If a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element.
and for Retention
it means
If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS.
Solution 2:[2]
Strictly speaking, there are no defaults for annotations not specified. The annotations simply aren't there.
But for these two in particular,
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/annotation/Retention.html says
If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS.
and equivalently for target,
If a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element.
Solution 3:[3]
Default compiler behavior (if annotation not present)
@Target
If an @Target meta-annotation is not present on an annotation type T , then an annotation of type T may be written as a modifier for any declaration except a type parameter declaration.
parameter declaration is ElementType.TYPE_PARAMETER (Applies to parameterized types, generic declarations)
Java SE 8/11
- https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Target.html
- https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/annotation/Target.html
@Retention
Indicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS.
Java SE 8/11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | maaartinus |
Solution 2 | Mike Samuel |
Solution 3 |