最近学反射遇到一个问题:
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;public class ReflectTest { public static void main(String[] args) throws Exception {
Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
Object obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields(); //写数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method wM = pd.getWriteMethod();//获得写方法
wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
//读数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method rM = pd.getReadMethod();//获得读方法
Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
System.out.println(num);
}
}这个程序中wM.invoke(obj,2)和 rM.invoke(obj),wM和rM是Method对象,Method对象中没有invoke()方法啊(刚查api)。我知道这句java语句的意思,但是不知道这语句怎么来的。向高手求救。。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;public class ReflectTest { public static void main(String[] args) throws Exception {
Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
Object obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields(); //写数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method wM = pd.getWriteMethod();//获得写方法
wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
//读数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method rM = pd.getReadMethod();//获得读方法
Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
System.out.println(num);
}
}这个程序中wM.invoke(obj,2)和 rM.invoke(obj),wM和rM是Method对象,Method对象中没有invoke()方法啊(刚查api)。我知道这句java语句的意思,但是不知道这语句怎么来的。向高手求救。。
http://baike.baidu.com/view/1865203.htm
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException