注解
注解的本质:接口,继承自Annotation接口的接口
自定义注解:
/*
@author Nian
@Date 2022/8/21 15:37
@purpose
@Note 1.We can direct transfer parameter value and that not specify field.
when we use it if annotation field named 'value'.
Like this:String value(); we use it like this:@MyAnnotation("hi").
But we just use this method at just have one field.
2.Can't named field as 'value' if have more one field.
3.Suggest named as 'value' if just have one field.
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
//String value();
String name();
int age();
}
元注解(注解的注解):
1.@Target:声明注解可以作用的位置
参数属于枚举类:ElementType
参数:
TYPE:作用于类、接口、注解、枚举
FIELD:作用于字段
METHOD:作用于方法
CONSTRUCTOR:作用于构造方法
ANNOTATION_TYPE:作用于注解
2.@Retention:声明注解作用的时间
参数属于枚举类:RetentionPolicy
SOURCE:作用至编译之前
CLASS:作用至运行前,编译后
RUNTIME:作用至运行时
3.@Inherited:声明注解可以被子类继承(可以从子类中获取在父类使用的注解)
4.@Documented:声明该注解在生成javadoc文档时也要被写入文档
使用反射解析注解:
import com.etime.PrintLine;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
@author Nian
@Date 2022/8/21 15:38
@purpose
@Note about analysis annotation method 2:
We can get annotation field by getMethods() because annotation field is a method,
but annotation is extends from Annotation interface,in this interface have some
method:
equals(),toString(),hashCode(),annotationType(), so if we get annotation field value by
invoke Method object,will throw IllegalArgumentException.
why?
because we use for loop to get all field value,we invoke all method this annotation include
extends from Annotation interface.
*/
public class MyAnnotationTest {
@MyAnnotation(name = "念",age = 18)
public void test(){
}
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<MyAnnotationTest> myAnnotationTestClass = MyAnnotationTest.class;
Method testMethod = myAnnotationTestClass.getDeclaredMethod("test");
if (testMethod.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = testMethod.getAnnotation(MyAnnotation.class);
//Get annotation field value
//method 1:
String name = annotation.name();
int age = annotation.age();
System.out.println(name);
System.out.println(age);
PrintLine.printLine();
//method 2:
Class<MyAnnotation> myAnnotationClass = MyAnnotation.class;
Method[] methods = myAnnotationClass.getMethods();
System.out.println(methods.length);
for(Method method : methods){
System.out.println(method);
Object value = method.invoke(annotation);
System.out.println(value);
}
}
}
}