一、注解定义:
//表示该注解可作用于方法、类和接口、局部变量上,构造函数上
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.LOCAL_VARIABLE,ElementType.CONSTRUCTOR})
//表示在运行时有效
@Retention(RetentionPolicy.RUNTIME)
//注解允许继承
@Inherited
//表示在文档中生成
@Documented
public @interface Custom {
String desc();
String author();
int age();
}
注意:
1.当注解只有一个成员时,则成员名必须取名为valuse(),使用时可以忽略成员名和赋值号=
2.成员类型是受限的,合法的类型包括基本数据类型(char、int、double、float等等,不包括:Character、Interger、Double、Long等)和String 、Class、Annotation、Enumeration。
3.注解可以没有成员,没有成员的注解成为标识注解
4.注解成员必须是无参无异常
二、解析注解:
public static void parseAnnotation(Class<?> clazz){
try {
//判断类或接口上是否有注解
boolean isAnnotationClass = clazz.isAnnotationPresent(Custom.class);
if(isAnnotationClass){
Custom custom = clazz.getAnnotation(Custom.class);
System.out.println(custom.desc() + custom.master() + custom.age());
}
//方法一:
//获取dogClass这个类中所有的方法
Method[] methods = clazz.getMethods();
for(Method method: methods){
//判断方法上是否有Custom注解
boolean isAnnotationMethod = method.isAnnotationPresent(Custom.class);
if(isAnnotationMethod){
Custom annotation = method.getAnnotation(Custom.class);
System.out.println(annotation.desc() + annotation.master() + annotation.age());
}
}
//方法二:
for(Method method :methods){
Annotation[] annotations = method.getAnnotations(); //获取这个方法上的所有注解
for(Annotation annotation : annotations){
if(annotation instanceof Custom){
System.out.println(((Custom) annotation).desc() + ((Custom) annotation).master() + ((Custom) annotation).age());
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
另:getMethods()和getDeclaredMethods()区别
public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。
public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。