问题:javabean当中继承与反射的使用,为什么只有父类的字段设置为public,在子类当中才能用反射机制得到呢???
前提:不要内省,只通过反射方式实现。
public class Person {
public String name ;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Student extends Person {
private String xuehao;
Student(){
super();
}
public String getXuehao() {
return xuehao;
}
public void setXuehao(String xuehao) {
this.xuehao = xuehao;
}
}
public class TestStudent {
@Test
public void test(){
Student stu = new Student();
stu.setAge(1);
stu.setName("yang");
stu.setXuehao("sadfasdf");
HashMap<String,String> map = BeanToContentValues(stu);
System.out.println(map.get("age"));
System.out.println(map.get("xuehao"));
System.out.println(map.get("name"));
}
public static <T> HashMap<String,String> BeanToContentValues(T object) {
HashMap<String,String> values = new HashMap<String,String>();
Field[] fieldss = object.getClass().getFields();
for (Field field : fieldss){
try {
values.put(field.getName(), String.valueOf(field.get(object)));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
}
}
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
values.put(field.getName(), String.valueOf(field.get(object)));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
}
}
return values;
}
}
只有当person的字段设置为public时,在TestSudent类当中才能反射获取其值,在父类字段为protected时,子类也可以访问的,为什么无法反射到呢??