2020-01-11_Spring5AnnotationUtil

2020-01-11  本文已影响0人  kikop

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;

/**

/**
 * 类注解判断
 *
 * @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.*;

/**

import java.lang.annotation.*;

/**

}
1.3.3 MyClassAnnotation
package com.tech.ability.myannotation;

import java.lang.annotation.*;

/*

/**

/**

/**

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;

/**

/**

/**
 * 方法注解
 * @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;

/**

/**
 * @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;

/**

/**
 * @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();
}

}

上一篇 下一篇

猜你喜欢

热点阅读