通过反射得到一个类的对象,如何对该对象对应的类的父类中的变量赋值?

长耳bunny 2014-09-26 10:13:18
如题所述,下面是例子:
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()只能获取出该类的变量(不包括继承自父类的变量),那么问题出现了,如何对父类中的变量赋值呢?????
...全文
558 9 打赏 收藏 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dellmysky 2014-09-28
  • 打赏
  • 举报
回复
	public static void main(String[] args) throws Exception {
		Class<?> clazz = null;
		clazz = Class.forName("bianchengzhimei.SuperMan");
		Object p1 = clazz.newInstance();
		Field personNameField = null;
	    for(;clazz != Object.class;clazz= clazz.getSuperclass()){
	    	try {
				personNameField = clazz.getDeclaredField("name");
			} catch (Exception e) {}
	    }
	    personNameField.setAccessible(true);
		personNameField.set(p1, "darlingFish");

		System.out.println(personNameField.get(p1));
	}
2.wa 2014-09-28
  • 打赏
  • 举报
回复
SuperMan superMan = new SuperMan(10, "LL");
        try {
            //Field field = person.getClass().getDeclaredField("name");
            Field field =  superMan.getClass().getSuperclass().getDeclaredField("name");
            field.setAccessible(true);
            field.set(superMan, "ERWA");
            System.out.println(superMan.getName());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
可以取到自己,再取个父类不就 OK?
bayougeng 2014-09-28
  • 打赏
  • 举报
回复
private是私有变量,如果想给子类用,你就应该定义成protected啊。 否则要这么多访问限定关键字干什么
福来哥 2014-09-28
  • 打赏
  • 举报
回复
7楼的方法基本上可以用了。另外推荐一种更规范的写法:

Class<?> clazz = null;
	    clazz = Class.forName("bianchengzhimei.SuperMan");
		//使用符合JavaBean规范的属性访问器
	    PropertyDescriptor pd = new PropertyDescriptor("name", clazz);
		//调用setter		
		Method writeMethod = pd.getWriteMethod();	//setName()
		writeMethod.invoke(obj, "test");
		//调用getter
		Method readMethod = pd.getReadMethod();		//getName()
		readMethod.invoke(obj);
2.wa 2014-09-27
  • 打赏
  • 举报
回复
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();
        }
要什么就反射取吧
jacob_cxt 2014-09-27
  • 打赏
  • 举报
回复
getdeclaredfields应该是不行的, 它好像只能得到当前类所有属性 getfields按理应该可以获取到当前类极其父类的所有属性, 当然前提是属性得是public的
长耳bunny 2014-09-27
  • 打赏
  • 举报
回复
引用 2 楼 u011278496 的回复:
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();
        }
要什么就反射取吧
我的意思是SuperMan的实例,想通过反射得到SuperMan父类Person的变量。。。
长耳bunny 2014-09-26
  • 打赏
  • 举报
回复
刚刚又看到一个方法,getFields,本以为能把集成的变量都找出来,结果不好使

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧