1
0

TreeUtils.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * 创建时间:2017-08-16 22:59
  3. * 项目名称:kmall_pt
  4. * 类名称:TreeUtils.java
  5. * 包名称:com.kmall.common.utils
  6. *
  7. * 修改履历:
  8. * 日期 修正者 主要内容
  9. *
  10. *
  11. * Copyright (c) 2016-2017 兆尹科技
  12. */
  13. package com.kmall.common.utils;
  14. import org.apache.commons.collections.CollectionUtils;
  15. import java.lang.reflect.Field;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Map;
  20. /**
  21. * 名称:TreeUtils <br>
  22. * 描述:<br>
  23. *
  24. * @author Scott
  25. * @version 1.0
  26. * @since 1.0.0
  27. */
  28. public class TreeUtils {
  29. /**
  30. * 包装成树形结构 (全部属性)
  31. * 必须要有id parentId children
  32. *
  33. * @param tree
  34. * @return
  35. * @throws Exception
  36. */
  37. public static List factorTree(List tree) {
  38. try {
  39. if (tree != null) {
  40. List t_list = new ArrayList();
  41. Map map = new HashMap();
  42. for (Object o : tree) {
  43. Class clazz = o.getClass();
  44. Field id = clazz.getDeclaredField("id");
  45. if (!id.isAccessible()) {
  46. id.setAccessible(true);
  47. }
  48. Integer lId = (Integer) id.get(o);
  49. map.put(lId, o);
  50. }
  51. for (Object o : map.keySet()) {
  52. Integer cId = (Integer) o;
  53. Object obj = map.get(cId);
  54. Class clazz = obj.getClass();
  55. Field pId = clazz.getDeclaredField("parentId");
  56. if (!pId.isAccessible()) {
  57. pId.setAccessible(true);
  58. }
  59. Integer id = (Integer) pId.get(obj);
  60. if (null == map.get(id)) {
  61. t_list.add(obj);
  62. } else {
  63. Object object = map.get(id);
  64. Class clazz1 = object.getClass();
  65. Field children = null;
  66. try {
  67. //没有children属性就到父类查找
  68. children = clazz1.getDeclaredField("children");
  69. } catch (Exception e) {
  70. children = clazz1.getSuperclass().getDeclaredField("children");
  71. }
  72. if (!children.isAccessible()) {
  73. children.setAccessible(true);
  74. }
  75. List list = (List) children.get(object);
  76. if (CollectionUtils.isEmpty(list)) {
  77. list = new ArrayList();
  78. }
  79. list.add(obj);
  80. children.set(object, list);
  81. }
  82. }
  83. return t_list;
  84. }
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. }
  88. return null;
  89. }
  90. }