如题所述,下面是例子:
class Person{
private int age;
private String name;
public Person(){
}
public Person(int age, String name){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class SuperMan extends Person implements ActionInterface
{
private boolean BlueBriefs;
public static void fly()
{
System.out.println("超人会飞耶~~");
}
public boolean isBlueBriefs() {
return BlueBriefs;
}
public void setBlueBriefs(boolean blueBriefs) {
BlueBriefs = blueBriefs;
}
@Override
public void walk(int m) {
// TODO Auto-generated method stub
System.out.println("超人会走耶~~走了" + m + "米就走不动了!");
}
}
interface ActionInterface{
public static int nonono = 1;
public void walk(int m);
}
接下来是主函数:
public static void main(String[] args) throws Exception {
Class<?> clazz = null;
clazz = Class.forName("bianchengzhimei.SuperMan");
Object p1 = clazz.newInstance();
Field personNameField = clazz.getDeclaredField("name");
personNameField.setAccessible(true);
personNameField.set(p1, "darlingFish");
System.out.println(personNameField.get(p1));
这样的话程序会出错误:
Exception in thread "main" java.lang.NoSuchFieldException: name
at java.lang.Class.getDeclaredField(Class.java:2057)
at bianchengzhimei.ZDGYSP151.main(ZDGYSP151.java:32)
问题的原因是getDeclaredField()只能获取出该类的变量(不包括继承自父类的变量),那么问题出现了,如何对父类中的变量赋值呢?????
------解决思路----------------------
Person person = new Person(10, "LL");
try {
Field field = person.getClass().getDeclaredField("name");
field.setAccessible(true);
field.set(person, "ERWA");
System.out.println(person.getName());
} catch (NoSuchFieldException
------解决思路----------------------
IllegalAccessException e) {
e.printStackTrace();
}
要什么就反射取吧
------解决思路----------------------
getdeclaredfields应该是不行的, 它好像只能得到当前类所有属性
getfields按理应该可以获取到当前类极其父类的所有属性, 当然前提是属性得是public的
------解决思路----------------------
SuperMan superMan = new SuperMan(10, "LL");
try {
//Field field = person.getClass().getDeclaredField("name");
Field field = superMan.getClass().getSuperclass().getDeclaredField("name");