Annotations
- Act as a metadata
- Preceded by @
- @Override
Check that the method signature override an interface method otherwise the compiler will send an error.
- @Deprecated
The compiler indicate that this method is deprecated
- @SuppressWarnings("deprecation")
Avoid that the compiler indicate the use of a deprecated method
- @Retention
To indicate the availability according to the RetentionPolicy Values
- Java Source - Exist only in source file / Discarted by compiler
- Class - (Default value) Compile into the class file / Discarted by runtime
- Runtime - Loaded into runtime / Accesible with reflection
- @Target
Define the elements where the annotation can be used:
Target(ElementType.CONSTRUCTOR)
Target( { ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE })
Create own annotations
- Declare the attibutes as methods
- Setting is similar to fields
Declare annotation
@Target(ElementType.TYPE)
@Retention( RetentionPolicy.RUNTIME )
public @interface MyAnnotation{
boolean useThisFeature();
Default value
//In this case we are establishing a default value.
boolean useThisFeature() default true;
}
Use annotation
@MyAnnotation( useThisFeature = false)
or
@MyAnnotation// Using the default value
public class MyClass (){
}
Valid Annotation Element Types
- Primitive Types
- String
- Enum
- Annotation
- Class<?>
- Array of all the above
Access to annotation
//This get if the class contains an annotation of type : MyAnnotation
MyAnnotation ma = myclassWithAnnotation.getAnnotation( MyAnnotation.class );
if( ma == null){
}
else if( ma.useThisFeature() ) {
}
Comentarios
Publicar un comentario