黑马程序员技术交流社区
标题:
反射问题,高手指点
[打印本页]
作者:
盛亚昆
时间:
2012-4-1 01:36
标题:
反射问题,高手指点
public class IntroSpectorTest {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Persion p=new Persion("王五",21);
String propertyName="name";
PropertyDescriptor pd = new PropertyDescriptor(propertyName,p.getClass());
Method methodSetNAME = pd.getWriteMethod();
methodSetNAME.invoke(pd,"王五");//有错误
System.out.println(pd.getName());
}
//我想用set方法把名字赋值到Persion 类里,做不出来了 ,高手指点啊???
public class Persion {
public String name;
private int age;
public Persion(String name,int age){
super();
this.name=name;
this.age=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;
}
}
作者:
yangshang1
时间:
2012-4-1 06:15
本帖最后由 yangshang1 于 2012-4-1 06:16 编辑
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntroSpectorTest {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Persion1 p=new Persion1("王五",21);
String propertyName="name";
PropertyDescriptor pd = new PropertyDescriptor(propertyName,p.getClass());
Method methodSetNAME = pd.getWriteMethod();
methodSetNAME.invoke(p,"王五");//换成p
System.out.println(pd.getName());
System.out.println(p.getName());
}
}
//我想用set方法把名字赋值到Persion 类里,做不出来了 ,高手指点啊???
class Persion1 {
public String name;
private int age;
public Persion1(String name,int age){
super();
this.name=name;
this.age=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;
}
}
作者:
何万县
时间:
2012-4-1 07:37
主函数的第五行methodSetNAME.invoke(pd,"王五");改成methodSetNAME.invoke(p,"王五");,invoke方法调用的是对象和参数,不是调用属性描述器。再看看视频吧,反射,内省和动态代理很重要,这些知识学不好的话以后会很吃力。
作者:
盛亚昆
时间:
2012-4-1 10:05
谢谢指点
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2