123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- package com.sinosoft.lz.system.util;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- /**
- *
- * @author zhangdapeng
- * @version 1.0,2014年5月13日
- * @since 1.0
- */
- public class NodeWorker{
- /**
- * 自身id
- */
- private String id;
- /**
- * 父id
- */
- private String pid;
- /**
- * 节点内容
- */
- private Object data;
- /**
- * 孩子节点列表
- */
- private ChildrenWorker children = new ChildrenWorker();
- public NodeWorker() {
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getPid() {
- return pid;
- }
- public void setPid(String pid) {
- this.pid = pid;
- }
- public Object getData() {
- return data;
- }
- public void setData(Object data) {
- this.data = data;
- }
- // 先序遍历,拼接JSON字符串
- public String toString() {
- Class<? extends Object> clazz = data.getClass();
- Field[] field = clazz.getDeclaredFields();
- String name = null;
- String value = null;
- StringBuilder result = new StringBuilder();
- for (int i = 0; i < field.length; i++) {
- name = field[i].getName();
- value = (String) invokeGet(data, name);
- if (i != 0) {
- result.append(",").append('"' + name + '"' + ":" + '"' + value + '"');
- } else
- result.append("{").append('"' + name + '"' + ":" + '"' + value + '"');
- }
- if (children != null && children.getSize() != 0) {
- result.append(",").append('"').append("c").append('"').append(":")
- .append(children.toString());
- } else {
- // result.append(",").append('"' + "leaf" + '"' + ":" + '"' + "true"
- // + '"');
- }
- return result.append("}").toString();
- }
- /**
- * java反射bean的get方法
- *
- * @param objectClass
- * @param fieldName
- * @return
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public Method getGetMethod(Class objectClass, String fieldName) {
- StringBuffer sb = new StringBuffer();
- sb.append("get");
- sb.append(fieldName.substring(0, 1).toUpperCase());
- sb.append(fieldName.substring(1));
- try {
- return objectClass.getMethod(sb.toString());
- } catch (Exception e) {
- }
- return null;
- }
- /**
- * 执行get方法
- *
- * @param o
- * 执行对象
- * @param fieldName
- * 属性
- */
- public Object invokeGet(Object o, String fieldName) {
- Method method = getGetMethod(o.getClass(), fieldName);
- try {
- return method.invoke(o, new Object[0]);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- // 添加孩子节点
- public void addChild(NodeWorker node) {
- this.children.addChild(node);
- }
- }
|