工具类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;
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();
}
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 {
Field fieldDec = tClass.getDeclaredField(key);
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;
}
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工具方法
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;
}