我根据你的意思大概模拟了一下 不知道是不是你想要的 没有空指针 但是这样只能得到父类的属性 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); }}
但是这样只能得到父类的属性
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);
}}
你是正确的,我忘记判断非空了,所以得出的是NULL,非常感谢.