其他的有些代码是关于Java web的,我感觉不影响我以上要表达的意思.简单点比较好

解决方案 »

  1.   

    我根据你的意思大概模拟了一下 不知道是不是你想要的 没有空指针
    但是这样只能得到父类的属性
    class Father {

    String s = "afa";

    int i = 10;

    public String getKeyToValue() { // reflection to get all the attributes
    Class c = this.getClass().getSuperclass();
    Field[] fields = c.getDeclaredFields();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < fields.length; i++) {
    Field f = fields[i];
    try {
    String value = f.get(this).toString().trim();
    if (null != f && !value.equals("")) {
    sb.append(" ").append(f.getName()).append("=\"")
    .append(value).append("\"");
    }
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    }
    return sb.toString();
    }
    }public class Child extends Father{

    String s = "safsfsfs";

    public static void main(String[] args) {
    String s = new Child().getKeyToValue();
    System.out.println("ada");
    System.out.println(s);
    }}
      

  2.   

    getDeclaredFields()是获取自身类的属性,getFields()会把继承的属性一起获取,看情况用
      

  3.   


    你是正确的,我忘记判断非空了,所以得出的是NULL,非常感谢.