平时工作中都会遇到包含层级机构的数据转换成树形结构,但是反过来也是很常见的,就是存在层级关系的数据已经是树形结构了,需要我们处理成一个普通的一层的list数据结构,下面就是我在工作中实际遇到的情况,我获取到的是树形结构的数据集合,需要转换成普通的list,本文也是通过反射来完成的,下面是详细的代码,和大家一起分享学习!
public final static String Children = "children";
public static <T> List<T> toList(List<T> trees) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<T> datalist = new ArrayList<T>();
if (CollectionUtils.isEmpty(trees))
return null;
T t = trees.get(0);
Class<? extends Object> clazz = t.getClass();
return toList(clazz, trees);
}
@SuppressWarnings("unchecked")
private static <T> List<T> toList(Class<? extends Object> clazz, List<T> trees) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<T> datalist = new ArrayList<T>();
if (CollectionUtils.isEmpty(trees))
return null;
for (T t : trees) {
// 设置直接点
List<T> childTree = (List<T>) ClassReflectUtils.getfieldValue(clazz, t, Children);
if (!CollectionUtils.isEmpty(childTree)) {
List<T> childList = toList(clazz, childTree);
if (!CollectionUtils.isEmpty(childList)) {
datalist.addAll(childList);
}
}
// ClassReflectUtils.setValue(clazz, t, Children, new ArrayList<clazz>());
datalist.add(t);
}
return datalist;
}
创建一个工具类,然后将两个方法粘贴进去即可,然后写一个测试类,造几条测试数据测试即可!
ClassReflectUtils类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ClassReflectUtils {
private final static Logger log = LoggerFactory.getLogger(ClassReflectUtils.class);
/**
* 获取类中所有字段集合
* @param clazz 类
* @return
*/
public static Map<String, Field> getFieldsMap(Class<? extends Object> clazz) {
Map<String, Field> fieldMap = new HashMap<String, Field>();
Field[] fieldArr = clazz.getDeclaredFields();
for (Field field : fieldArr) {
fieldMap.put(field.getName(), field);
}
Class<?> superClazz = clazz.getSuperclass();
if (null != superClazz) {
Map<String, Field> superFieldMap = getFieldsMap(superClazz);
fieldMap.putAll(superFieldMap);
}
return fieldMap;
}
/**
* 获取对象中对应字段的set方法
* @param clazz 类
* @param fieldName 字段名称
* @param fieldClass 字段类
* @return
* @throws NoSuchFieldException
* @throws NoSuchMethodException
*/
public static Method getDeclaredSetMethod(Class<? extends Object> clazz, String fieldName, Class<?>... fieldClass) throws NoSuchFieldException, NoSuchMethodException {
if(hasField(clazz,fieldName)){
String nkey = String.valueOf(fieldName.charAt(0)).toUpperCase() + ((fieldName.length() == 1) ? "" : fieldName.substring(1));
return clazz.getDeclaredMethod("set" + nkey, fieldClass);
}else{
if(null != clazz.getSuperclass()){
return getDeclaredSetMethod(clazz.getSuperclass(),fieldName);
}else{
throw new NoSuchFieldException(clazz.getName()+"对象中无"+ fieldName+"属性");
}
}
}
/**
* 为对象的对应字段赋值
* @param clazz 对象
* @param instance 实体
* @param fieldName 字段名称
* @param fieldValue 字段值
* @param fieldType 字段类型
* @throws Exception
*/
public static void setValue(Class<? extends Object> clazz, Object instance, String fieldName, Object fieldValue, Class<?> fieldType) throws Exception {
// logger.info("{}设置{}的值{},值类型:{}", clazz.getName(), fieldName, fieldValue.toString(), fieldType.getName());
Method setChildMethod = ClassReflectUtils.getDeclaredSetMethod(clazz, fieldName, fieldType);
setChildMethod.invoke(instance, fieldValue);
}
/***
* 获取对应字段的get方法
* @param clazz 对象
* @param fieldName 字段名称
* @return
* @throws NoSuchMethodException
*/
public static Method getDeclaredGetMethod(Class<? extends Object> clazz, String fieldName) throws NoSuchFieldException, NoSuchMethodException {
if(hasField(clazz,fieldName)){
String nkey = String.valueOf(fieldName.charAt(0)).toUpperCase() + ((fieldName.length() == 1) ? "" : fieldName.substring(1));
Method getKeyMethod = clazz.getDeclaredMethod("get" + nkey);
return getKeyMethod;
}else{
if(null != clazz.getSuperclass()){
return getDeclaredGetMethod(clazz.getSuperclass(),fieldName);
}else{
throw new NoSuchFieldException(clazz.getName()+"对象中无"+ fieldName+"属性");
}
}
}
/**
* 判断对象中是否存在对应的字段
* @param clazz
* @param key
* @return
*/
private static boolean hasField(Class<?> clazz, String key) {
if(null == clazz){
return false;
}
// logger.info(clazz.getName());
Field[] fieldArr = clazz.getDeclaredFields();
for (Field field : fieldArr) {
if(StringUtils.equals(field.getName(),key))
return true;
}
return false;
}
/**
* 获取对象中对应字段的值
* @param clazz 对象类型
* @param instance 实体
* @param fieldName 字段名称
* @param <T>
* @return
* @throws NoSuchFieldException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static <T> Object getfieldValue(Class<?> clazz, T instance, String fieldName) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// logger.info("{}获取{}的get方法", clazz.getName(), fieldName);
Object fieldKeyValue = null;
Method getKeyMethod = ClassReflectUtils.getDeclaredGetMethod(clazz, fieldName);
if (null != instance) {
fieldKeyValue = getKeyMethod.invoke(instance);
}
return fieldKeyValue;
}
/**
* 获取对象中对应字段的值,并转换成String类型返回
* @param clazz 对象类型
* @param instance 实体
* @param fieldName 字段名称
* @param <T>
* @return
* @throws NoSuchFieldException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static <T> String getfieldStringValue(Class<?> clazz, T instance, String fieldName) {
/// logger.info("{}获取{}的值", clazz.getName(), fieldName);
String fieldStringValue = null;
try {
Method method = ClassReflectUtils.getDeclaredGetMethod(clazz, fieldName);
Object fieldValue = method.invoke(instance);
Type type = method.getGenericReturnType();
if (type.equals(Date.class)) {
fieldStringValue = DateUtils.formatDate((Date) fieldValue, DateUtils.TIME_PATTERN);
} else {
fieldStringValue = TransUtils.transString(fieldValue);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
log.error("系统异常:",e);
} catch (Exception e) {
log.error("系统异常:",e);
}
return fieldStringValue;
}
}
网友评论