import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
public class ReflectUtils {
/**
* 为一个对象的所有属性添加默认值
* @param obj
*/
public static void setDefaultValue(Object obj)
throws IllegalAccessException, ClassNotFoundException, InstantiationException {
Class<?> objClass = obj.getClass();
List<Field> declaredFields = new ArrayList<>();
while (objClass != null){
declaredFields.addAll(new ArrayList<>(Arrays.asList(objClass.getDeclaredFields())));
objClass = objClass.getSuperclass();
}
for (Field field : declaredFields) {
field.setAccessible(true);
Object o = field.get(obj);
if(o == null){
// 属性类型
Type genericType = field.getGenericType();
String type = genericType.toString();
switch (type){
case "class java.lang.String":
if(field.getName().toLowerCase().contains("datetime")){
field.set(obj, LocalDateTime.now().toString().replace("T"," "));
}else if(field.getName().toLowerCase().contains("date")){
field.set(obj, LocalDate.now().toString());
}else{
field.set(obj, RandomStringUtils.random(2,"uft-8"));
}
break;
case "class java.lang.Integer": field.set(obj, RandomUtils.nextInt(0,10));break;
case "class java.lang.Boolean": field.set(obj, false);break;
case "class java.lang.Long": field.set(obj,RandomUtils.nextLong(0,99));break;
case "class java.util.Date": field.set(obj,new Date());break;
default:
if(type.startsWith("class")){
String name = type.replace("class ", "");
Object o1 = Class.forName(name).newInstance();
setDefaultValue(o1);
field.set(obj,o1);
}else if(type.startsWith("java.util.List")){
List list = new ArrayList();
collectionSerDefaultValue(list,field);
field.set(obj,list);
}else if(type.startsWith("java.util.Set")){
Set set = new HashSet();
collectionSerDefaultValue(set,field);
field.set(obj,set);
}
}
}
}
}
private static void collectionSerDefaultValue(Collection collection, Field field)
throws IllegalAccessException, InstantiationException, ClassNotFoundException {
// 属性类型
Type genericType = field.getGenericType();
ParameterizedType parameterizedType = (ParameterizedType)genericType;
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
if(actualTypeArguments != null){
for (Type tempType : actualTypeArguments) {
String name = tempType.toString().replace("class ", "");
Class<?> clazz = Class.forName(name);
Object temp;
if(clazz.isEnum()){
Object[] values = clazz.getEnumConstants();
temp=values[0];
}else{
temp = clazz.newInstance();
setDefaultValue(temp);
}
collection.add(temp);
}
}
}
}
反射赋值
最新推荐文章于 2022-12-07 12:47:02 发布