package com.eaton.guan.club.util;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
/**
* @Author : hyx
* @CreateDate : 2021-06-02 11:19
*/
public class ListUtil {
/**
* list排序 一个list基于另一个list排序
* @param orderRegulation 有序list
* @param targetList 无序list
* @param fieldName 排序字段名称
* @param <T>
*/
public static <T> void setListOrder(List <Long> orderRegulation, List <T> targetList, String fieldName) {
targetList.sort(((o1, o2) -> {
int io1 = orderRegulation.indexOf(getObjectId(o1,fieldName));
int io2 = orderRegulation.indexOf(getObjectId(o2,fieldName));
if (io1 != -1) {
io1 = targetList.size() - io1;
}
if (io2 != -1) {
io2 = targetList.size() - io2;
}
return io2 - io1;
}));
}
/**
* 通过反射获取泛型中对象字段的值
* @param inputObject 泛型对象
* @param fieldName 需要获取的字段名称
* @return
*/
public static <T> Long getObjectId(T inputObject, String fieldName) {
Class <?> clazz = inputObject.getClass();
PropertyDescriptor pd = null;
try {
Field field = inputObject.getClass().getDeclaredField(fieldName);
pd = new PropertyDescriptor(field.getName(), clazz);
} catch (Exception e) {}
//传入类没有指定字段,就去父类上找
if (StringUtils.isEmpty(pd)){
try {
Field declaredField = inputObject.getClass().getSuperclass().getDeclaredField(fieldName);
Class <?> aClass = inputObject.getClass().getSuperclass();
pd = new PropertyDescriptor(declaredField.getName(), aClass);
} catch (Exception e) {}
}
//获得get方法
Method getMethod = pd.getReadMethod();
return (Long) ReflectionUtils.invokeMethod(getMethod, inputObject);
}
}