Spring5AnnotationUtils
1 注解概述
AnnotationUtils是一个专门用于处理复杂注解问题的类。其主要由公共和静态方法组成,它允许在类,方法或字段上检查注解。另外,AnnotationUtils不仅仅来做简单的类分析。它也通过查找在超类和接口上的注解来做更多的事情。基于反射的API,AnnotationUtils使用java.lang.reflect的 3个元素来处理注解:
Annotation:表示注解。
AnnotatedElement:表示被注解元素。
Method:提供某些类或接口中的方法的信息。
1.1 MyAnnotationUtils
package com.tech.ability.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
/**
- @author kikop
- @version 1.0
- @project Name: TechnicalAbilityToolBox
- @file Name: MyAnnotationUtils
- @desc 功能描述 springmvc自身也提供该工具类
- @date 2020/1/11
- @time 10:50
- @by IDE: IntelliJ IDEA
*/
public class MyAnnotationUtils {
/**
* 类注解判断
*
* @param clazz
* @param annotationClass
* @return
*/
public static boolean hasAnnotation(Class<?> clazz, Class<? extends Annotation> annotationClass) {
return clazz.isAnnotationPresent(annotationClass);
}
/**
* 方法注解判断
*
* @param method
* @param annotationClass
* @return
*/
public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotationClass) {
return method.isAnnotationPresent(annotationClass);
}
/**
* 获取类注解
*
* @param clazz
* @param annotationClass
* @param <T>
* @return
*/
public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationClass) {
return clazz.getDeclaredAnnotation(annotationClass);
}
/**
* 获取方法注解
*
* @param method
* @param annotationClass
* @param <T>
* @return
*/
public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) {
return method.getDeclaredAnnotation(annotationClass);
}
/**
* 获取字段注解
*
* @param field
* @param annotationClass
* @param <T>
* @return
*/
public static <T extends Annotation> T getAnnotation(Field field, Class<T> annotationClass) {
return field.getDeclaredAnnotation(annotationClass);
}
/**
* 修改注解属性
*
* @param annotation
* @param attrName
* @param attrValue
*/
@SuppressWarnings("unchecked") // 告诉编译器忽略警告。不用在编译完成后出现警告。
public static void modifyAnnotationProperties(Annotation annotation, String attrName, Object attrValue) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
Field declaredField = null;
try {
declaredField = invocationHandler.getClass().getDeclaredField("memberValues");
if (declaredField != null) {
declaredField.setAccessible(true);
Map<String, Object> memberKeyValues = (Map<String, Object>) declaredField.get(invocationHandler);
memberKeyValues.put(attrName, attrValue);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
1.2 Spring5注解工具类
1.3 辅助类
1.3.1 MyFieldAnnotation
package com.tech.ability.myannotation;
import java.lang.annotation.*;
/**
- @author kikop
- @version 1.0
- @project Name: TechnicalAbilityToolBox
- @file Name: MyFieldAnnotation
- @desc 功能描述 内注解
- @date 2020/1/11
- @time 18:32
- @by IDE: IntelliJ IDEA
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyFieldAnnotation {
String color() default "green";
String author() default "kikop";
String version() default "v1";
}
1.3.2 MyMethodAnnotation
package com.tech.ability.myannotation;
import java.lang.annotation.*;
/**
-
@author kikop
-
@version 1.0
-
@project Name: TechnicalAbilityToolBox
-
@file Name: MyMethodAnnotation
-
@desc 功能描述 方法注解定义
-
@date 2020/1/11
-
@time 18:38
-
@by IDE: IntelliJ IDEA
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyMethodAnnotation {String className() default "classNameOld";
String value() default "valueOld";
}
1.3.3 MyClassAnnotation
package com.tech.ability.myannotation;
import java.lang.annotation.*;
/*
- @Retention(RetentionPolicy.SOURCE): 意思是让MyAnnotation注解只在java源文件中存在,编译成.class文件后注解就不存在了
- @Retention(RetentionPolicy.CLASS): 意思是让MyAnnotation注解在java源文件(.java文件)中存在,编译成.class文件后注解也还存在,被MyAnnotation注解类标识的类被类加载器加载到内存中后MyAnnotation注解就不存在了
- @Retention(RetentionPolicy.RUNTIME):意思是让MyAnnotation这个注解的生命周期一直程序运行时都存在
*/
/**
-
@author kikop
-
@version 1.0
-
@project Name: TechnicalAbilityToolBox
-
@file Name: MyClassAnnotation
-
@desc 功能描述 类注解
-
@date 2020/1/11
-
@time 18:38
-
@by IDE: IntelliJ IDEA
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyClassAnnotation {String className() default "Empty class name";
/**
- 出生地
- @return
*/
String bornPlace() default "NJ";
String[] hobbies() default {"Football", "Tennis", "PingPang"};
String hobbiesSplit() default "Football,Tennis,PingPang";
/**
- 缺省值
- 如果一个注解中有一个名称为value的属性,且你只想设置value属性(即其他属性都采用默认值或者你只有一个value属性)
- 那么可以省略掉“value=”部分
- @return
/
String value();
/* - 国籍
- @return
*/
MyCountryEnum bornCountry() default MyCountryEnum.CHINA;
}
1.3.4 MyCountryEnum
package com.tech.ability.annotation;
/**
- Created by kikop on 2018/12/16.
*/
/**
- @author kikop
- @version 1.0
- @project Name: TechnicalAbilityToolBox
- @file Name: MyCountryEnum
- @desc 功能描述 枚举定义
- @date 2020/1/11
- @time 18:38
- @by IDE: IntelliJ IDEA
*/
public enum MyCountryEnum {
/**
* 中国
/
CHINA(1),
/*
* 美国
*/
AMERICAN(2);
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
private int value;
/**
* 构造函数
* @param value
*/
MyCountryEnum(int value) {
this.value = value;
}
public static void main(String[] args) {
for(MyCountryEnum enumCountry : MyCountryEnum.values()){
System.out.println(enumCountry.getValue());
}
MyCountryEnum china= MyCountryEnum.CHINA;
System.out.println(china.getClass().toString());
}
}
1.3.5 MyRequest
package com.tech.ability.myannotation;
/**
- @author kikop
- @version 1.0
- @project Name: TechnicalAbilityToolBox
- @file Name: MyRequest
- @desc 功能描述
- @date 2020/2/11
- @time 21:09
- @by IDE: IntelliJ IDEA
*/
public class MyRequest {
}
1.3.6 MyUserInfo
package com.tech.ability.myannotation;
/**
-
@author kikop
-
@version 1.0
-
@project Name: TechnicalAbilityToolBox
-
@file Name: MyUserInfo
-
@desc 功能描述
-
@date 2020/1/11
-
@time 19:22
-
@by IDE: IntelliJ IDEA
*/
@MyClassAnnotation(
className = "MyClsAnnotation",
bornCountry = MyCountryEnum.AMERICAN,
hobbies = {"c", "d", "a", "b", "xyz"},
hobbiesSplit = "11,22", value = "yes"
)
public class MyUserInfo {
private String strName;
private Integer age;public Integer getAge() {
return age;
}public void setAge(Integer age) {
this.age = age;
}public String getStrName() {
return strName;
}public void setStrName(String strName) {
this.strName = strName;
}public MyUserInfo(String strName, int age) {
this.age = age;
this.strName = strName;
}/**
- 字段注解
*/
@MyFieldAnnotation(color = "black")
public String strColor;
- 字段注解
/**
* 方法注解
* @param myRequest
* @return
*/
@MyMethodAnnotation(className = "classNameNew", value = "valueNew")
public String testMethod(MyRequest myRequest) {
return getStrName();
}
}
1.4 测试
1.4.1 MyAnnotationUtils
package com.tech.ability.myannotation;
import com.tech.ability.util.MyAnnotationUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
- @author kikop
- @version 1.0
- @project Name:
- @file Name: CustomAnnotationTest
- @desc 功能描述 自定义注解
- @date 2020/1/11
- @time 18:49
- @by IDE: IntelliJ IDEA
*/
public class CustomAnnotationTest {
/**
* @param
* @return void
* @description 获取类注解
* @author kikop
* @date 2020/1/11
* @time 19:04
*/
public static void getClassAnnotationTest() throws Exception {
boolean hasAnnotation = MyAnnotationUtils.hasAnnotation(MyUserInfo.class, MyClassAnnotation.class);
if (hasAnnotation) {
//1.读取类注解
MyClassAnnotation myClassAnnotation = MyAnnotationUtils.getAnnotation(MyUserInfo.class, MyClassAnnotation.class);
System.out.println(myClassAnnotation.value());
System.out.println(myClassAnnotation.bornCountry());
System.out.println(myClassAnnotation.bornPlace());
//1.1.打印数组值
String[] hobbiesArray = myClassAnnotation.hobbies();
for (String str : hobbiesArray) {
System.out.println(str);
}
//1.2.将数组转为list
List<String> hobbiesLst = Arrays.asList(hobbiesArray);
List<String> hobbiesLstResult =
hobbiesLst.stream().filter(par -> !par.equals("a")).sorted().limit(3).collect(toList());
hobbiesLstResult.forEach(par -> System.out.println(par));
//2.读取字段注解并修改
//1.获取类中某个方法定义Method
Field colorField = MyUserInfo.class.getField("strColor");
MyFieldAnnotation myFieldAnnotation = MyAnnotationUtils.getAnnotation(colorField, MyFieldAnnotation.class);
MyAnnotationUtils.modifyAnnotationProperties(myFieldAnnotation, "color", "yellow");
System.out.println(myFieldAnnotation.color());
}
}
public static void main(String[] args) throws Exception{
getClassAnnotationTest();
}
}
1.4.2 SpingAnnotationTest
package com.tech.ability.myannotation;
import org.springframework.core.annotation.AnnotationUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
-
@author kikop
-
@version 1.0
-
@project Name:
-
@file Name: SpingAnnotationTest
-
@desc 功能描述 Spring注解
-
@date 2020/1/11
-
@time 18:49
-
@by IDE: IntelliJ IDEA
*/
public class SpingAnnotationTest {/**
-
@param
-
@return void
-
@description 获取cls注解
-
@author kikop
-
@date 2020/1/11
-
@time 19:04
*/
public static void getClassAnnotationTest() {//1.读取
MyClassAnnotation myPersonAnnotation = AnnotationUtils.findAnnotation(MyUserInfo.class, MyClassAnnotation.class);
if (myPersonAnnotation != null) {System.out.println(myPersonAnnotation.value()); System.out.println(myPersonAnnotation.bornCountry()); System.out.println(myPersonAnnotation.bornPlace()); //1.1.打印数组值 String[] hobbiesArray = myPersonAnnotation.hobbies(); for (String str : hobbiesArray) { System.out.println(str); } //1.2.将数组转为list List<String> hobbiesLst = Arrays.asList(hobbiesArray); List<String> hobbiesLstResult = hobbiesLst.stream().filter(par -> !par.equals("a")).sorted().limit(3).collect(toList()); hobbiesLstResult.forEach(par -> System.out.println(par));
}
}
/**
-
@param
-
@return void
-
@description 获取方法注解
-
@author kikop
-
@date 2020/1/11
-
@time 20:12
*/
private static void getMethodAnnotationTest() throws NoSuchMethodException {//1.获取类中某个方法定义Method
Method testMethod = MyUserInfo.class.getMethod("testMethod", new Class[]{MyRequest.class});//2.获取方法上的注解
MyMethodAnnotation myMethodAnnotation = AnnotationUtils.findAnnotation(testMethod, MyMethodAnnotation.class);//3.获取注解某个属性默认值
System.out.println(AnnotationUtils.getDefaultValue(myMethodAnnotation, "className"));//4.获取注解某个属性实际值
System.out.println(AnnotationUtils.getValue(myMethodAnnotation, "className"));
}
-
/**
* @param
* @return void
* @description 获取字段注解
* @author kikop
* @date 2020/1/11
* @time 20:12
*/
private static void getFieldAnnotationTest() throws Exception {
//1.获取类中某个方法定义Method
Field colorField = MyUserInfo.class.getField("strColor");
//2.获取方法上的注解
MyFieldAnnotation myColorAnnotation = AnnotationUtils.findAnnotation(colorField, MyFieldAnnotation.class);
//3.获取注解某个属性默认值
System.out.println(AnnotationUtils.getDefaultValue(myColorAnnotation, "color"));
//4.获取注解某个属性实际值
System.out.println(AnnotationUtils.getValue(myColorAnnotation, "color"));
}
public static void main(String[] args) throws Exception {
//getClassAnnotationTest();
//getMethodAnnotationTest();
getFieldAnnotationTest();
}
}
网友评论