131 lines
4.2 KiB
Java
Raw Normal View History

2023-02-16 15:28:15 +08:00
package com.zhgd.xmgl.util;
import com.zhgd.xmgl.modules.worker.entity.WorkerMonthAttendanceStatistics;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @program: wisdomSite
* @description: 反射操作
* @author: Mr.Peng
* @create: 2022-02-15 17:32
**/
public class ReflectUtils {
/**
* @param o 操作对象
* @param methodName 方法名
* @param attName 属性名
* @param value
* @return get方法返回实际值 set方法返回操作后对象
**/
private static Object Operation(Object o, String methodName, String attName, Class<?> paramType, Object value) {
// 方法赋值出错标志
boolean opErr = false;
Object res = null;
Class<?> type = o.getClass();
try {
Method method = null;
if (methodName.indexOf("get") != -1) {
// get方法
// 获取方法
method = type.getMethod(methodName);
// 执行
res = method.invoke(o);
} else {
// set方法
// 当没有传入参数类型时通过value获取参数类型
paramType = paramType == null ? value.getClass() : paramType;
// 获取方法
method = type.getMethod(methodName, paramType);
// 执行
method.invoke(o, value);
res = o;
}
} catch (Exception e) {
// 通过get/set方法操作属性失败
opErr = true;
}
if (opErr) {
// 通过打破封装方式直接对值进行操作
try {
Field field = null;
// 获取属性
field = type.getDeclaredField(attName);
// 打破封装
field.setAccessible(true);
if (methodName.indexOf("get") != -1) {
// get方法
// 获取属性值
res = field.get(o);
} else {
// set方法 
// 设置属性值
field.set(o, value);
res = o;
}
} catch (Exception e) {
//两种方法都操作失败
}
}
return res;
}
public static <T> T set(T o, String attName, Object value, Class<?> paramType) {
if (o == null || attName == null || attName.isEmpty()) {
return null;
}
String methodName = attNameHandle("set", attName);
return (T) Operation(o, methodName, attName, paramType, value);
}
@SuppressWarnings("unchecked")
public static <T> T get(Object o, String attName, Class<T> returnType) {
if (o == null || attName == null || attName.isEmpty()) {
return null;
}
String methodName = attNameHandle("get", attName);
return (T) Operation(o, methodName, attName, null, null);
}
/**
* 属性名处理
* @param method 方法(get/set)
* @param attName
* @return
*/
private static String attNameHandle(String method, String attName) {
StringBuffer res = new StringBuffer(method);
// 属性只有一个字母
if (attName.length() == 1) {
res.append(attName.toUpperCase());
} else {
// 属性包含两个字母及以上
char[] charArray = attName.toCharArray();
// 当前两个字符为小写时,将首字母转换为大写
if (Character.isLowerCase(charArray[0]) && Character.isLowerCase(charArray[1])) {
res.append(Character.toUpperCase(charArray[0]));
res.append(attName.substring(1));
} else {
res.append(attName);
}
}
return res.toString();
}
public static void main(String[] args) {
WorkerMonthAttendanceStatistics statistics=new WorkerMonthAttendanceStatistics();
String inputTime="2022-02-05";
statistics.setQueryTime(inputTime.substring(0,7));
statistics=set(statistics,"day"+Integer.valueOf(inputTime.substring(8,10)),1,null);
System.out.println(statistics.toString());
}
}