自定义注解,根据反射拿到被注解修饰的类,方法,属性
自定义注解
//作用在类,类的成员变量上 ElementType.TYPE该注解作用于类
//ElementType.FIELD 该注解作用于类的属性
//ElementType.METHOD 该注解作用于方法
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
//生命周期
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotNote {
String value() default "0";
int age() default 0;
}
在方法上加上
@Bean
@AnnotNote
public Student anStu(){
return new Student("张",12,"男");
}
在属性上加上
package com.lqy.redis.bean;
/**
* @title: DataBean
* @Author Tan
* @Date: 2020/8/5 11:55
* @Version 1.0
*/
/**
* C
* FileName: DataBean
* Author:
* Date: 2020/6/17 16:02
* Description:
* History:
* <author> <version> <desc>
* zhaoyi 1.0 描述
*/
import lombok.Data;
import lombok.ToString;
/**
* 〈功能简述〉<br>
* 〈数据实体〉
*
* @author 35903
* @create 2020/6/17
* @since 1.0
*/
@Data
@ToString
public class DataBean {
/**
* 数据值
*/
@AnnotNote()
private double dataValue;
/**
* 数据值时间
*/
@AnnotNote()
private String dataValueTime;
/**
* 入库时间
*/
String insertTime;
/**
* 相应的数据点号
*/
private String dataId;
/**
* 时间间隔(5分钟,15分钟...)
*/
private int dataInterval;
}
测试
@Autowired
PublicReflectionUtils publicReflectionUtils;
@Autowired
ApplicationContext ac;
ApplicationContext applicationContext = SpringApplicationContextUtil.getApplicationContext();
String[] beanNamesForType = ac.getBeanNamesForType(Student.class);
Class<DruidConfig> druidConfigClass = DruidConfig.class;
Method[] methods = druidConfigClass.getMethods();
//拿到被注解修饰的方法Bean
for (Method name:methods
) {
if(name.isAnnotationPresent(AnnotNote.class)){
String name1 = name.getName();
Object b = ac.getBean(name1);
System.out.println("拿到Bean"+b);
System.out.println("被修饰的方法"+name1);
}
}
//模拟传入的对象
DataBean dataBean = new DataBean();
dataBean.setDataValue(15);
dataBean.setInsertTime("adsd");
dataBean.setDataValueTime("sad");
dataBean.setDataId("454");
//根据反射拿到这个类
Class<? extends DataBean> aClass = dataBean.getClass();
//拿到这个类中所有属性
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field:declaredFields
) {
//判断属性上是否加了AnnotNote这个注解
if(field.isAnnotationPresent(AnnotNote.class)){
String s = field.getName().toString();
//通过反射根据这个属性名,跟类,拿到这个类中这个属性的值
Object fieldValueByName = publicReflectionUtils.getFieldValueByName(s, dataBean);
System.out.println(s+"属性的值:"+fieldValueByName);
//拿到属性上被这个注解修饰的注解值
AnnotNote annotation = field.getAnnotation(AnnotNote.class);
System.out.println("annotation:"+annotation.value());
//属性描述器
PropertyDescriptor ps = new PropertyDescriptor(field.getName(),aClass);
// getReadMethod 获得用于读取属性值的方法; getWriteMethod(),获得用于写入属性值的方法;
Method readMethod = ps.getReadMethod();
Object invoke = readMethod.invoke(dataBean);
System.out.println("读取:"+invoke);
// Method writeMethod = ps.getWriteMethod();
// Object aaabbb = writeMethod.invoke(dataBean, 111);
// System.out.println("写入:"+aaabbb);
// System.out.println(annotation);
}
}
用到的反射工具类
package com.lqy.redis.util;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
/**
* 〈功能简述〉<br>
* 〈反射工具类〉
*
* @author All en
* @create 2020/5/6
* @since 1.0
*/
@Component
public class PublicReflectionUtils {
/**
* 功能描述:
* 〈根据输入对象,查找对象的属性。(包含父类属性)〉
*
* @param o 对象
* @return : java.util.List<java.lang.reflect.Field> 对象属性
* @author : All En
* date : 2020/5/6 13:43
*/
public static Field[] listReflectionField(Object o) throws ClassNotFoundException {
Class clazz = o.getClass();
Field[] fields = getAllFields(clazz);
return fields;
}
public static Object getGetMethod(Object ob, String name) throws InvocationTargetException, IllegalAccessException {
Method[] m = ob.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
if (("get" + name).toLowerCase(Locale.ENGLISH).equals(m[i].getName().toLowerCase(Locale.ENGLISH))) {
return m[i].invoke(ob);
}
}
return null;
}
/**
* 功能描述:
* 〈获取输入对象的属性〉
*
* @param clazz 对象
* @return : java.lang.reflect.Field[] 对象数据
* @author : All En
* date : 2020/5/6 13:43
*/
private static Field[] getAllFields(Class<?> clazz) throws ClassNotFoundException {
List<Field> fieldList = new ArrayList<>();
//对象路径容器
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
//获取Field属性是对象属性。
// fieldList.addAll(listClassForName(fieldList));
Field[] fields = new Field[fieldList.size()];
return fieldList.toArray(fields);
}
/**
* 功能描述:
* 〈判断Field属性,是否存为对象〉
*
* @param fieldList Field属性
* @return : java.util.List<java.lang.String> 对象数据
* @author : All En
* date : 2020/5/6 14:12
*/
private static List<Field> listClassForName(List<Field> fieldList) throws ClassNotFoundException {
List<Field> comFieldList = new ArrayList<>();
for (Field var : fieldList) {
//判断类型是否为对象路径
if (var.getGenericType().toString().contains("com")) {
String[] split = var.getGenericType().toString().split(" ");
if( split.length >2) {
Class z = Class.forName(split[1]);
while (z != null) {
comFieldList.addAll(new ArrayList<>(Arrays.asList(z.getDeclaredFields())));
z = z.getSuperclass();
}
}
}
}
return comFieldList;
}
/**
* 功能描述:〈根据属性名获取对象的属性值〉
*
* @param fieldName 属性名
* @param o 对象
* @return : java.lang.Object 属性值
* @author : LL
* date : 2020.03.19 16:29
*/
public static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
/**
* 功能描述:
* 〈循环遍历对象中的属性值,〉
*
* @param o 对象
* @param UnwantedColumn 对象中不需要的列名
* @return : java.util.List<java.lang.String>
* @author : All En
* date : 2020/6/8 10:33
*/
public static List<String> reflectionFieldResult(Object o, List<String> UnwantedColumn) throws ClassNotFoundException {
List<String> data = new ArrayList<>();
Field[] fields = listReflectionField(o);
for (Field f : fields) {
List<String> column = UnwantedColumn.stream().filter(v -> v.equals(f.getName())).collect(Collectors.toList());
if (column.size() == 0) {
Object value = getFieldValueByName(f.getName(), o);
if (null == value)
data.add("");
else
data.add(String.valueOf(value));
}
}
return data;
}
public static void main(String[] args) {
String a = null;
System.out.println(String.valueOf(a));
}
}
用到的读取上下文
package com.lqy.redis.util;
import org.springframework.context.ApplicationContext;
/**
* 从Spring上下文取出Bean工具类
*
* @author ZhuPengWei
* @date 2018/6/27 18:04
*/
public class SpringApplicationContextUtil {
private static ApplicationContext applicationContext = null;
public static void setApplicationContext(ApplicationContext applicationContext) {
if (SpringApplicationContextUtil.applicationContext == null) {
SpringApplicationContextUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}