当前位置: 代码迷 >> J2SE >> 对于java反射的invoke方法报错
  详细解决方案

对于java反射的invoke方法报错

热度:361   发布时间:2016-04-24 18:13:14.0
关于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"});这样
  相关解决方案