Turn:
There are four meta-annotations in java: @Retention @Target @Document @Inherited;
@Retention: the retention position of the annotation
@Retention(RetentionPolicy.
SOURCE
)
//Annotations only exist in the source code, not in the class bytecode file
@Retention(RetentionPolicy.
CLASS
) // The default retention policy, annotations will exist in the class bytecode file, but cannot be obtained at runtime,
@Retention(RetentionPolicy.RUNTIME)
// The annotation will exist in the class bytecode file and can be obtained by reflection at runtime
@Target: the target of the annotation
@Target(ElementType.TYPE)
//
Interface, class, enumeration, annotation
@Target(ElementType.FIELD)
//
Field, enumeration constant
@Target(ElementType.METHOD)
//
方法
@Target(ElementType.PARAMETER)
//
Method parameters
@Target(ElementType.CONSTRUCTOR)
//
Constructor
@Target(ElementType.LOCAL_VARIABLE)
//
local variable
@Target(ElementType.ANNOTATION_TYPE)
//
注解
@Target(ElementType.PACKAGE) /
//
包
@Document: indicates that the annotation will be included in the javadoc
@Inherited: Indicates that subclasses can inherit the annotation in the parent class
Example:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AnnatDemo{
public int value();
}
@Target({ElementType.METHOD})
public @interface AnnatDemo{
public int value();
}
The above code defines the @AnnatDemo annotation, the purpose of which is to annotate the method and keep it in the runtime environment. We can use reflection to obtain the annotation on a method and call the defined method.
For example @AnnatDemo acts on the following methods:
public interface IClientProtocolEx extends IProtocol {
int METHOD_START=0;
@AnnatDemo(METHOD_START)
public String say(String person);
public String say(String person);
}
Then you can use the following code for reflection:
Class ipt=IClientProtocalEx.class;
Method[] mts=ipt.getMethod();
for(Method mt:mts)
{
AnnatDemo ad=mt.getAnnotation(AnnatDemo.class);//If there is no such annotation on the method, return null
int value=ad.value();
System.out.println("value:"+value);
}
Annotations are part of building a base jar. Projects have their own framework, and if used properly, annotations are a good part of it!