自定义注解
@interface 使用 @interface 关键字定义注解
String value() default "";
成员变量 只有一个必须是value 默认值:defaule ""
成员变量类型是受限的,合法的类型包括原始类型及String,Class,annotation,Enumeration。
可以没有成员变量 :称之为标识注解
@Target 作用域
@Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)
@Target(ElementType.TYPE)
@Target(ElementType.FIELD)
@Target(ElementType.METHOD)
@Target(ElementType.PARAMETER)
@Target(ElementType.CONSTRUCTOR)
@Target(ElementType.LOCAL_VARIABLE)
@Target(ElementType.ANNOTATION_TYPE)
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.CLASS)
@Retention(RetentionPolicy.RUNTIME)
@Inherited 允许被子类继承
@Documented 表示生成javadoc时会包含注解
实践
1. 定义一个注解类
@Target({ElementType.METHOD})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
String value();
}
2. 定义一个类 在类的一个方法中加上注解
public class Demo {
@MyAnnotion("test")
public void test() {
}
}
3. 获取注解内容
public class Test {
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("com.smile.annotion.Demo");
Method test = aClass.getMethod("test");
boolean annotationPresent = test.isAnnotationPresent(MyAnnotion.class);
if (annotationPresent){
MyAnnotion annotation = test.getAnnotation(MyAnnotion.class);
System.out.println(annotation.value());
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}