注解的分类
注解可分为:源码注解、编译时注解、运行时注解。
源码注解:注解只在源码中存在,编译成.class文件就不存在了。
编译时注解:注解在源码和.class文件中都存在,如@Override。
运行时注解:在运行阶段还会起作用,甚至会影响运行逻辑的注解。
一、新建自定义注解
假设现在我要自定义一个叫做Description的注解,那么我就要新建一个注解类。
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String value();
}
@Target({ElementType.METHOD,ElementType.TYPE}):表示我这个注解可以用在类或方法上。
@Retention(RetentionPolicy.RUNTIME):表示这是一个运行时注解
@Inherited:表示这个注解允许子类继承,并且子类只能继承父类在类上的注解
@Documented:表示项目导出成javadoc时可以用到
此外,如果注解里只有一个方法,那么必须定义方法名为value
二、使用自定义注解
1.新建一个Penson接口。
/**
* 创建人:taofut
* 创建时间:2018-12-15 13:25
*/
public interface Person {
String name();
Integer age();
}
2.新建接口实现类Child,并且在类和方法上都加上我自定义的这个注解@Description
/**
* 创建人:taofut
* 创建时间:2018-12-15 13:26
*/
@Description("我是类注解")
public class Child implements Person {
@Override
@Description("我是方法注解")
public String name() {
return null;
}
@Override
public Integer age() {
return null;
}
}
三、解析自定义注解
自定义注解已经使用了,但是怎么让它生效呢?这就需要去解析它。
/**
* 创建人:taofut
* 创建时间:2018-12-15 13:24
*/
public class ParseAnnotation {
public static void main(String[] args) {
//1.使用类加载器加载类
try {
Class c=Class.forName("com.ft.annotation.Child");
//2.找到类上面的注解
//该类上是否存在Description这个注解
Boolean isExist=c.isAnnotationPresent(Description.class);
if(isExist){
//3.拿到注解实例
Description description=(Description)c.getAnnotation(Description.class);
System.out.println(description.value());
}
//4.找到方法上的注解
//遍历所有的方法
Method [] methods=c.getMethods();
for(Method m:methods){
Boolean isMExist=m.isAnnotationPresent(Description.class);
if(isMExist){
Description description=(Description)m.getAnnotation(Description.class);
System.out.println(description.value());
}
}
//另外一种解析方式
for(Method m:methods){
//先拿到方法上的所有注解
Annotation[] annotations=m.getAnnotations();
for(Annotation anno:annotations){
//遍历每个注解,找到Description注解
if(anno instanceof Description){
Description description=(Description)anno;
System.out.println(description.value());
break;
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果:
我是类注解
我是方法注解
我是方法注解