首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

对于java反射的invoke方法报错

2011-11-21 
关于java反射的invoke方法报错Java codepublic void invokeMethod(Object owner)throws Exception{Class o

关于java反射的invoke方法报错

Java code
public void invokeMethod(Object owner)throws Exception{        Class obj = owner.getClass();        Method[] me = obj.getDeclaredMethods();        for(Method object : me){            object.setAccessible(true);            Class [] param= object.getParameterTypes();            if (param.length != 0) {                object.invoke(owner, (Object)param);            }else{                object.invoke(owner);            }        }    }


以上是我的解析方法,IDE报错为:
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at JavaReflection.JavaReflection.invokeMethod(JavaReflection.java:43)
at JavaReflection.JavaReflection.main(JavaReflection.java:82)

[解决办法]
你根本搞错方法的意思

Class [] param= object.getParameterTypes();
这里返回的是这个方法所需要的参数类型列表


object.invoke(owner, (Object)param);
这里要传递的是这个方法的参数值!不是类型

例如有一个方法public void a(int x, String y);

Class[] param <==> {int.class, String.class}

而在invoke的时候你需要传递的是实际的值!例如invoke(owner, new Object[]{1, "xyz"});这样

热点排行