我们最常使用的注解是@Override,他的源码如下
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
从其源码我们可以看到
1.自定义注解一般用@interface表示
2.其上一般有@Target 和 @Retention
@Retention:表示注解的保留策略,有三个,如下
@Retention(RetentionPolicy.SOURCE) //表示注解仅存在于源码中,在class字节码文件中不存在
@Retention(RetentionPolicy.CLASS) // 表示注解存在于class字节码文件中,但运行时无法获得(默认)
@Retention(RetentionPolicy.RUNTIME) //表示注解存在于class字节码文件中,在运行时可以通过反射获取到
@Target:表示注解的作用目标
@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) // 包
@Documented:表示注解包含在javadoc中
@Inherited:表示注解可以被继承
例如自定义实现一个@Autowired注解,如下
package com.derry.annotation;
import java.lang.annotation.*;
/**
* @Author:derry
* @Description:
* @Date: Created in 11:09 2019/2/19
* @Modified By:
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
String value() default "";
}
使用该注解
package com.derry.test;
import com.derry.annotation.Autowired;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* @Author:derry
* @Description:
* @Date: Created in 11:09 2019/2/19
* @Modified By:
*/
public class Test {
@Autowired("derry")
private static String name;
@Autowired("男")
private static String sex;
public static void print(){
System.out.println("该用户为:"+name+" 性别为:"+sex);
}
public static void initAnnotation() {
Class<?> clazz = Test.class;
Field[] fields = clazz.getDeclaredFields();
for (Field field:fields
) {
if (!field.isAnnotationPresent(Autowired.class)){
continue;
}else{
Autowired autowired = field.getAnnotation(Autowired.class);
Object value = autowired.value();
if(field.getName().equals("name")){
name = (String) value;
}
if (field.getName().equals("sex")){
sex = (String) value;
}
}
}
}
public static void main(String[] args) {
//初始化加载注解
initAnnotation();
print();
}
}
输出结果为: