一、自定义注解的介绍
@interface自定义注解
- @interface自定义注解自动继承java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。
- 在定义注解时,不能继承其他注解和接口
- 使用@interface来声明一个注解
- 每一个方法实际上是声明了一个配置参数
- 方法的名称就是参数的名称
- 返回值的类型就是参数的类型(返回值类型只能是基本类型,Class,String,enum)
- 可以通过default来声明参数的默认值
@Target
说明了Annotation所修饰的对象范围,取值(ElementType)有:
- CONSTRUCTOR:用于描述构造器
- FIELD:用于描述域
- LOCAL_VARIABLE:用于描述局部变量
- METHOD:用于描述方法
- PACKAGE:用于描述包
- PARAMETER:用于描述参数
- TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Retention
设置注解的生命周期
- RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃
- RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期
- RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
二、创建自定义注解
- 下面分别描述 作用于类、方法、属性上的注解
作用在属性上注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FiledAnnotation {
String value() default "GetFiledAnnotation";
}
作用在方法上的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {
String name() default "MethodAnnotation";
String url() default "https://blog.csdn.net/qq_38617531";
}
作用在类上的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TypeAnnotation {
String value() default "Is-TypeAnnotation";
}
三、使用自定义注解
@TypeAnnotation(value = "doTest")
public class Test {
@FiledAnnotation(value = "小林家的史莱姆")
private String myfield = "";
@MethodAnnotation()
public String getDefaultInfo() {
return "do the getDefaultInfo method";
}
@MethodAnnotation(name = "CSDN", url = "https://blog.csdn.net")
public String getDefineInfo() {
return "do the getDefineInfo method";
}
}
四、测试自定义注解
public class TestMain {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("com.luyz.common.annotation.Test");
Method[] method = cls.getMethods();
/**判断Test类上是否有TypeAnnotation注解*/
boolean flag = cls.isAnnotationPresent(TypeAnnotation.class);
/**获取Test类上是TypeAnnotation注解值*/
if (flag) {
TypeAnnotation typeAnno = (TypeAnnotation) cls.getAnnotation(TypeAnnotation.class);
System.out.println("@TypeAnnotation值:" + typeAnno.value());
}
/**方法上注解*/
List<Method> list = new ArrayList<Method>();
for (int i = 0; i < method.length; i++) {
list.add(method[i]);
}
for (Method m : list) {
MethodAnnotation methodAnno = m.getAnnotation(MethodAnnotation.class);
if (methodAnno == null)
continue;
System.out.println( "方法名称:" + m.getName());
System.out.println("方法上注解name = " + methodAnno.name());
System.out.println("方法上注解url = " + methodAnno.url());
}
/**属性上注解*/
List<Field> fieldList = new ArrayList<Field>();
for (Field f : cls.getDeclaredFields()) {
// 访问所有字段
FiledAnnotation filedAno = f.getAnnotation(FiledAnnotation.class);
System.out.println( "属性名称:" + f.getName());
System.out.println("属性注解值FiledAnnotation = " + filedAno.value());
}
}
}