import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author TheRaging
* @Package cn.zjky.sme.conmon.util
* @date 2022/2/7 15:14
* @description
*/
@Component
public class TreeUtils<E> {
/**
* 通过反射获取泛型的属性值
*/
private Long getParentId(E e,String parentName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class clazz = e.getClass();
//得到所有的属性
Field[] tableFields = clazz.getDeclaredFields();
Long parentId = new Long(0);
for (int i = 0; i < tableFields.length; i++) {
//获取属性的名字
String name = tableFields[i].getName();
// 获取属性类型
String type = tableFields[i].getGenericType().toString();
//判断类型 进行强转
if(name.equals(parentName)){
//将属性名字的首字母大写
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
//整合出 getXXX() 属性这个方法
Method m = clazz.getMethod("get"+name);
//如果设置的类型是我需要的
if(type.equals("class "+Long.class.getName())){
parentId = (Long) m.invoke(e);
}else if(type.equals("class "+long.class.getName())){
parentId = (Long) m.invoke(e);
}else if(type.equals("class "+Integer.class.getName())){
parentId = Long.valueOf(m.invoke(e).toString());
}else if(type.equals("class "+int.class.getName())){
parentId =new Long((long)m.invoke(e));
}else{
throw new ClassCastException(parentName+":"+type+",支持的类型:Long,long,Integer,int");
}
//中断循环
break;
}
}
if(parentId == null){
throw new NullPointerException("没有找到"+parentName+"属性");
}
return parentId;
}
/**
* @param: list 集合 所有的数据
* @param: parentname 代表父ID的属性名
* @param: idName 代表id的属性名
* @description:
* @return: java.util.List<E>
* @author: TheRaging
* @date: 2022/2/7
*/
public List<E> getAllByid(List<E> list ,Long id, String parentname ,String idName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//list为null
if(list.size()<1){
return list;
}
//E 保证的有id和parentid
E first = null;
for(E e : list){
Long ids = this.getParentId(e,idName);
if(ids.equals(id)){
//终止循环
first = e;
break;
}
}
if(first == null ){
throw new NullPointerException("集合中不存在id:"+id+"的数据");
}
//广(宽)度优先算法 BFS
List<E> result = new ArrayList<>();
Stack<E> head = new Stack();
head.push(first);
while (!head.isEmpty()){
//先弹出头部
E e = head.pop();
//查询有几个子节点
for (E obj: list) {
if(getParentId(obj, parentname).equals(getParentId(e, idName))){
//有子节点 压进去栈里边
head.push(obj);
//子节点添加进集合里边
result.add(obj);
}
}
}
return result;
}
}
网友评论