最近学反射遇到一个问题:
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语句的意思,但是不知道这语句怎么来的。向高手求救。。

解决方案 »

  1.   

    楼主可以参考一下下边的链接
    http://baike.baidu.com/view/1865203.htm
      

  2.   

    呵呵,建议编辑软件eclipse随笔之后,防止此错误
      

  3.   

    我了个去,api看不到,源代码总看得到吧java.lang.reflect.Method.java里面绝对有啊。public Object invoke(Object obj, Object... args)
    throws IllegalAccessException, IllegalArgumentException,
               InvocationTargetException
      

  4.   

    不用查api吧,光标移到invoke方法上按f3不就找到源代码了吗