元注解
元注解是放在注解上面的注解
常用的有@Target和@Rentention
-
@Target:约束作用位置,值是 ElementType 枚举常量,包括
- METHOD 方法
- VARIABLE 变量
- TYPE 类/接口
- PARAMETER 方法参数
- CONSTRUCTORS 构造方法
- LOACL_VARIABLE 局部变量等。
-
@Rentention:约束生命周期,值是 RetentionPolicy 枚举常量,包括 SOURCE 源码、CLASS 字节码和 RUNTIME 运行时。
-
@Documented:表明这个注解应该被 javadoc 记录。
写一个自己的注解
数组可以有那些类型
- int
- short
- byte
- long
- float
- double
- boolean
- char
- String
- Class
- 枚举
- 以及上面的每一种的数组形式
用反射获取方法上的注解
public class GetmyAnnotation {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
Class<?> clazz = Class.forName("javase.注解.GetmyAnnotation");
Method myAnnotation = clazz.getDeclaredMethod("myAnnotation");
//获取方法对象
javase.注解.myAnnotation annotation = myAnnotation.getAnnotation(myAnnotation.class);
//获取注解对象
String age = annotation.age();
String name = annotation.name();
System.out.println(age+name);
}
@myAnnotation(name="张三",age="23")
public void myAnnotation(){
}
}