自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
String name();
String value();
}
在类上加入注解
@MyAnnotation(name = "小灰灰", value = "喜洋洋")
public class MyObject implements MyInterface
获取类的注解
Class<MyObject> aClass = MyObject.class;
// 获取所有的注解
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获取指定的注解
MyAnnotation myAnnotation = aClass.getAnnotation(MyAnnotation.class);
String name = myAnnotation.name();
String value = myAnnotation.value();
System.out.println(name);
System.out.println(value);
结果如下
@com.nextyu.study.reflection.MyAnnotation(name=小灰灰, value=喜洋洋)
小灰灰
喜洋洋
源码地址
更多
微信公众号:卖字母维生(living-coding),更多教程、工具、资源分享