注解用了这么多,第一次探索下它的自定义
注解有4种元注解:
@Target:表示该注解可以用于什么地方,属性ElementType参数有以下
CONSTRUCTOR:构造器的声明
FIELD:域声明(包括enum实例)
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类、接口(包括注解类型)或enum声明
@Retention:表示需要在什么级别保存该注解信息,属性RetentionPolicy参数有以下
SOURCE:注解将被编译器丢弃
CLASS:注解在class文件中可用,但会被VM丢弃
RUNTIME:VM将在运行期间保留注解,因此可以通过反射机制读取注解的信息
@Documented:该注解将被包含在javadoc中
@Inherited:子类可以继承父类中的该注解
话不多说,直接来个最简单的自定义注解:
package com.liqiye.springbootdemo.utils;
// 自定义注解
import java.lang.annotation.*;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SetName {
// 默认注入
public String value() default "";
}
写一个实体类(这里我用了lombok,省事)
package com.liqiye.springbootdemo.entity;
import com.liqiye.springbootdemo.utils.SetName;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* @author liqiye
* @description
* @date 2019/4/6
*/
@Data
@Slf4j
public class User {
public Integer id;
@SetName(value = "张三")
public String name;
public Integer age;
}
写一个测试类
package com.liqiye.springbootdemo.test;
import com.liqiye.springbootdemo.entity.User;
import com.liqiye.springbootdemo.utils.SetName;
import org.junit.Test;
import java.lang.reflect.Field;
/**
* @author liqiye
* @description 测试自定义注解
* @date 2019/4/7
*/
public class TestAnnotation {
public static String getInfo(Class<?> cs){
String result = "";
Field[] declaredFields = cs.getDeclaredFields();
for (Field field : declaredFields){
if(field.isAnnotationPresent(SetName.class)){
SetName annotation = field.getAnnotation(SetName.class);
String value = annotation.value();
result += (field.getName() + ":" + value + "\n");
}
}
return result;
}
@Test
public void test() {
String info = TestAnnotation.getInfo(User.class);
System.out.println(info);
}
}
打印出下图,看到注解已起作用
有空再去深究注解,自定义出功能强大的注解!