反射機制——利用反射造樹

反射機制——利用反射造樹

最近做項目需要做樹形數據,故而想要做一個通用方法出來,供大家一起使用下面。具體代碼如下:

public class TreeUtil {
	/**
	 * 
	 * @param <T>
	 * @param list//列表總體數據
	 * @param root//根節點主鍵
	 * @param setChildrenMethod//保存子列表方法方法名
	 * @param getPrimaryKey//獲取主鍵方法名
	 * @param getParentKey//獲取父鍵方法名
	 * @throws Exception
	 * @return
	 */
	public static <T> List<T> listToTree(List<T> list,String rootGuid,String setChildrenMethod,String getPrimaryKey,String getParentKey) throws Exception{
		List<T> tree = new ArrayList<T>();
		list.stream().forEach(e->{
				if(rootGuid.equals(e.getClass().getMethod(getParentKey).invoke(e))) {
					e.getClass().getMethod(setChildrenMethod, List.class).invoke(e,listToTree(list,(String)e.getClass().getMethod(getPrimaryKey).invoke(e),setChildrenMethod,getPrimaryKey,getParentKey));
					tree.add(e);
				}
			}
			);
		return tree;
		
	}
}

具體需要的參數都在註釋上了,寫完後當然要計算這套代碼實不實用,具體執行效率如何。奈何最後結果讓我不得不放棄當初的想法。僅僅20條數據,反射調用相比於直接調用直接慢了20倍。所以建議大家反射機制要謹慎使用,不到萬不得已還是使用直接調用來的快

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章