Java提供了四个用于修饰自定义注解的元注解:
@Target、@Retention 、@Documented和@Inherited
@Target:
用于指定被修饰的自定义注解只能用于修饰程序中哪些元素,常用属性值有:
ElementType.FIELD:应用于全局属性
ElementType.METHOD:应用于方法
ElementType.PARAMETER:应用于方法的参数
ElementType.TYPE:应用于类、接口或者枚举声明
@Retention
@Retention:用于指定被修饰的自定义注解可以保留多久,该元注解有如下属性值:
RetentionPolicy.SOURCE:编译器将直接丢弃被修饰的注解。
RetentionPolicy.CLASS:默认值,编译器将把注解记录在class文件中,当运行Java程序时,虚拟机不再保留注解;
RetentionPolicy.RUNTIME:编译器将把注解记录在class文件中,当运行java程序时,虚拟机保留注解,程序可以通过反射获取该注解;
@Documented
执行javadoc命令时,被该元注解修饰的自定义注解也会生成在文档中
@Inherited
如果父类所使用的注解有@Inherited修饰,则子类可以继承该注解,否则不能继承。
注解的定义用到元注解
@Documented//是否在生成文档时被包含进去??
@Retention(RetentionPolicy.RUNTIME)//标识注解是否进行编译,编译后是否能够通过反射获取
@Target({ElementType.METHOD})//作用在方法上
public @interface InterfaceTest {
String name();
String describe();
}
通过反射拿到注解的方法
public class TestG {
public static void main(String[] args) {
new TestG().parse("1.23");
new TestG().enumTest(1);
new TestG().declareHandler(TestG.class);
System.out.printf("name is %s","lisa");
System.out.println(String.format("name is %s,second name is %s,third name is %s","lisa","jak","james"));//日志记录的方法
}
@InterfaceTest(name = "parse",describe = "data parse to other dataType")
private void parse(String s){
// System.out.println(Long.valueOf(s));
System.out.println(Double.valueOf(s));
}
private void enumTest(Integer key){
System.out.println(TestEnum.A1.getValueByKey(key));
}
public void declareHandler(Class<?> clazz){
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(InterfaceTest.class)){//当前InterfaceTest注释是否在这个method对象上
InterfaceTest interfaceTest = method.getAnnotation(InterfaceTest.class);//获取InterfaceTest注释
System.out.println("被标记的方法名为:"+interfaceTest.name());
System.out.println("被标记的方法描述为:"+interfaceTest.describe());
}
}
}
}