JAVA注解 JAVA自定义注解
1、语法:
@Target({ElementType.FIELD}) //作用目标
@Retention(RetentionPolicy.RUNTIME) //保留
@Inherited //允许子类继承,可以不加
@Documented //注解应该被 javadoc工具记录,可以不加
public @interface ChineseName { public String value();}

2、作用目标
ElementType.CONSTRUCTOR 构造方法声明
ElementType.FIELD 字段声明
ElementType.LOCAL_VARIABLE 局部变量申明
ElementType.METHOD 方法声明
ElementType.PACKAGE 包声明
ElementType.PARAMETER 参数声明
ElementType.TYPE 类接口

3、保留
RetentionPolicy.SOURCE 只在源码显示,编译时会丢弃
RetentionPolicy.CLASS 编译时会记录到class中,运行时忽
RetentionPolicy.RUNTIME 运行时存在,可以通过发射读取

4、这里以注解作用目标在属性上,运行时存在

5、新增一个Person实体,将注解放在name上

6、通过反射获取注解值

7、关键代码
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ChineseName {
public String value();
}
测试方法
@Test
public void testName() throws Exception {
Person person = new Person();
Class clazz = person.getClass();
Field field = clazz.getDeclaredField("name");
ChineseName annotation = field.getAnnotation(ChineseName.class);
System.out.println(annotation.value());
}