有3个类,一个测试类Text,一个父类FStudent,一个子类Student
父类有私有属性private String name 用set/get封装起来了
子类继承了父类
我想在测试类利用反射,设置父类的方法,或拿到父类的的值,我该怎么做,代码如下
package s2jsp.lg.dao.imp1;
public class Student extends TeStudent {
}
class TeStudent{
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package s2jsp.lg.dao.imp1;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
Class c = Class.forName("s2jsp.lg.dao.imp1.Student");
Object obj = c.newInstance();
Method mm = c.getDeclaredMethod("setName",String.class);
mm.invoke(obj, "11");
}
}
这里我只用了父类,而无法从子类中来调用setName();
package question1;
public class FStudent {
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package question1;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException{
Class c=Class.forName("question1.FStudent");
Object obj = c.newInstance();
//赋值
Method mm = c.getDeclaredMethod("setName",String.class);
mm.invoke(obj, "abc");
//取值
Field f=c.getDeclaredField("name");
f.setAccessible(true);
System.out.println("name= "+f.get(obj));
}
}
Method mm = c.getDeclaredMethod("setName",String.class);
mm.invoke(obj, "11");
这个就是反射调用了,obj的name就是11了。
//话说,你是在问我们吗?!