黑马程序员技术交流社区
标题:
Method.invoke()返回对象的问题
[打印本页]
作者:
张亚青
时间:
2013-3-27 12:39
标题:
Method.invoke()返回对象的问题
BeanInfo beanInfo=Introspector.getBeanInfo(classPerson);
PropertyDescriptor [] pds=beanInfo.getPropertyDescriptors();
Object result=new Object();
for(PropertyDescriptor pd:pds)
if(pd.getName().equals("setAge"))
{
Method methodSetAge=pd.getWriteMethod();
result=methodSetAge.invoke(p,25);
}
复制代码
以上代码中methodSetAge.invoke(p,25)返回的值为一个Object对象,如果我想要Person类型的对象,为什么
p=(Person)result;
这样转化的时候会报错????
我要怎么做?
作者:
itserious
时间:
2013-3-27 13:29
以上代码中methodSetAge.invoke(p,25)返回的值为一个Object对象,如果我想要Person类型的对象,为什么
p=(Person)result;
这样转化的时候会报错????
我要怎么做?
回答:methodSetAge.invoke(p,25)是写方法,是没有返回值的,这里也只会返回null, 所以不能进行p=(Person)result;
你想要有返回值,你只能用 读方法。Method methodGet=pd.getReadMethod();
result= methodGet.invoke(p);//这才是读方法。但要注意,读方法是没有参数的。
package test;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test6 {
/**
* @param args
* @throws IntrospectionException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws IntrospectionException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
Person p = new Person(20, "zhang");
System.out.println("改变前:" + p);
BeanInfo beanInfo = Introspector.getBeanInfo(p.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object result = new Object();
for (PropertyDescriptor pd : pds) {
//System.out.println("pd.getName()="+pd.getName());//这里的pd.getName返回的是属性名字。age,name
if (pd.getName().equals("age")) {
//1
Method methodSetAge = pd.getWriteMethod();//这里你是获得的写方法setAge。
result = methodSetAge.invoke(p, 25);//还要注意你的setAge方法是没有返回值的。所以result=null
//2
Method methodGet=pd.getReadMethod();
result= methodGet.invoke(p);//这才是读方法。但要注意,读方法是没有参数的。
//提示,你的result的值是你的Person的属性值。而不是Person对象。你怎么把它转成Person
System.out.println("result="+result);
System.out.println("改变后:" + p);
}
}
}
}
class Person {
int age = 3;
String name = "zzz";
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;
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
}
复制代码
作者:
VOIDMAIN
时间:
2013-3-29 22:52
本帖最后由 VOIDMAIN 于 2013-3-29 22:53 编辑
methodSetAge.invoke(p,25);只是通过Method的实例对象,也就是methodSetAge去调用方法,被调用的方法是在Method实例化的时候传进去的,也就是pd.getWriteMethod();
invoke,可以理解为方法的方法;
你要想通过反射获得实例对象,给你个参考写法(如果直接用Person类型的话,需要做类型的强转):
Object obj=Person.class.getConstructor().newInstance();
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2