注解可以作用在类、接口、属性、方法等,主要用于:
- 制定一些规范。
- 提取属性的值。
- 给属性、参数设置一些默认值。
- 设置描述信息。
1.自定义注解MyAnnotation的使用实例:
MyAnnotation:
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String description();
}
MyBean:
public class MyBean {
@MyAnnotation(description = "测试")
private String desc;
}
MyTest:
import java.lang.reflect.Field;
public class MyTest {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> cls = Class.forName("main.java.MyBean");
Field[] fields = cls.getDeclaredFields();
for(Field field : fields){
if(field.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation myAnnotation = field.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.description());
}
}
}
}
2. 注解定义:与接口的定义差不多,将interface前面加一个@符号。
3. 定义在注解上的注解:
@Documented
:是否在文档上面出现该注解。@Target
:注解可以使用的范围:- 类(ElementType.TYPE)
- 属性(ElementType.FIELD)
- 方法(ElementType.METHOD)
- 形参(ElementType.PARAMETER)
- 构造方法(ElementType.CONSTRUCTOR)
- 局部变量(ElementType.LOCAL_VARIABLE)
- 注解(ElementType.ANNOTATION_TYPE)
- 包(ElementType.PACKAGE)
源码如下:
@Retention
:注解生效的时刻。- 不编译(RetentionPolicy.SOURCE)
- 编译期(RetentionPolicy.CLASS)
- 运行时期(RetentionPolicy.RUNTIME)。
源码如下:
@Inherited
是否对该类的子类生效。