反射工具类
时间:2024-12-31 11:23 作者:紫琪软件工作室 分类: 工具集
工具类ReflectUtil
package cn.ziqirj.common.utils;
import cn.ziqirj.common.exception.UtilException;
import lombok.Setter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 反射工具类
* @author zhangji
*
*/
public class ReflectUtil<T> {
@Setter
private T t;
private final Class<T> tClass;
public ReflectUtil(Class<T> tClass) {
this.tClass = tClass;
}
/**
* 获取对象实例
*/
public T getObject() throws InstantiationException, IllegalAccessException {
return tClass.newInstance();
}
/**
* 生成对象
* @param map:key属性名->value值
* @return T
*/
public T getObject(Map<String, Object> map) throws InstantiationException, UtilException, IllegalAccessException{
Set<String> set = map.keySet();
T tt = tClass.newInstance();
for (String key : set) {
try {
// 这里必须调用getDeclaredFiedl();
Field fieldDec = tClass.getDeclaredField(key);
// 是否取消java的语法检查,因为此变量是私有的,如果不取消则无法赋值
fieldDec.setAccessible(true);
Object value = map.get(key);
fieldDec.set(tt, value);
} catch (NoSuchFieldException | SecurityException e) {
throw new UtilException(getObjectPath() + ":" + key + " is not found!", e);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new UtilException("赋值失败!", e);
}
}
return tt;
}
/**
* 解析注解:key:"name" ---> value:name值
* @param annoStr 注解字符串
*/
private Map<String, String> getParamsAnno(String annoStr) throws IllegalArgumentException {
Map<String, String> map = new HashMap<>();
annoStr = annoStr.substring(annoStr.indexOf('(')+1, annoStr.length()-1);
String[] annoStrArr = StringUtils.toArray(annoStr, ",");
if (annoStrArr != null) {
for(String str : annoStrArr) {
String[] strArr = StringUtils.toArray(str, "=");
if (strArr != null && strArr.length == 2) {
map.put(strArr[0].trim(), strArr[1]);
}
}
}
return map;
}
public String getObjectPath() {
return t.getClass().getName();
}
}
toArray工具方法
/**
* 字符串分割为字符串数组
*
* @param str 需要分割的字符串
* @param decollator 分割符, 默认为逗号
* @return 字符串数组
*/
public static String[] toArray(String str, String decollator) {
if(isEmpty(str) || isEmpty(decollator)) {
return null;
}
//需分割的字符串最后一个字符不能为分隔符
if(str.lastIndexOf(decollator) == str.length() - 1) {
str = str.substring(0, str.length() - 1);
}
if(isEmpty(str) || isEmpty(decollator)) {
return null;
}
//需分割的字符串第一个字符不能为分隔符
if(str.lastIndexOf(decollator) == 0) {
str = str.substring(1);
}
if(isEmpty(str) || isEmpty(decollator)) {
return null;
}
String[] array;
if(!str.contains(decollator)) {
array = new String[1];
array[0] = str;
} else {
array = str.split(decollator);
}
return array;
}