首页 > 解决方案 > java.lang.NoSuchMethodException: [Ljava.lang.reflect.Method;.myMethod(java.lang.String, boolean)

问题描述

我正在尝试从使用 Java 1.7 的类中获取方法。

非常奇怪的是,如果我打印 methodName 及其参数,与我使用的相同,但我总是得到:java.lang.NoSuchMethodException:

这是我的代码:

    public void invokeMethod(String className, String myMethod, List<Object> parametersMethod) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
    Class<?> cls = Class.forName(className);

    Method[] allMethods = cls.getDeclaredMethods();
    for(Method m : cls.getDeclaredMethods()){

        Type[] types = m.getParameterTypes();
        String tmp="";

        for (Type type : types) {
            tmp+=type+" ";
        }

        log.info(" " +m.getName()+" "+tmp); // 
    }
    Object obj = cls.newInstance();
    log.info("myMethod "+myMethod);

    Method m= allMethods.getClass().getMethod(myMethod, String.class, boolean.class); 
    log.info("m "+m.getName()+ "  "+m.getParameterTypes()+ "  "+m.getDefaultValue());
    m.invoke(obj, parametersMethod); }

这是我试图调用的方法:

public void tryIt(String myString, boolean mybool) throws Exception {
       //Do something
}

log.info 打印:tryIt class java.lang.String boolean

但是我得到了(当我尝试使用时Method m= allMethods.getClass().getMethod(myMethod, String.class, boolean.class);)

java.lang.NoSuchMethodException: [Ljava.lang.reflect.Method;.tryIt(java.lang.String, boolean)

我尝试使用布尔值而不是布尔值,但没有任何变化。

invokeMethod 位于使用 Jboss 7 的 Web 服务上,我的所有课程都是@StateLess.

标签: javajbossstateless

解决方案


allMethods是类型Method[],没有方法tryIt(String, boolean)。你想getMethod()打电话cls

另外,您调用的方法是错误的,因为Method.invoke()期望参数数组不是 a List,您可能需要这样的方法:

public void invokeMethod(String className, String myMethod, Object... parametersMethod) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    Class<?> cls = Class.forName(className);

    Object obj = cls.newInstance();

    Method m = cls.getMethod(myMethod, String.class, boolean.class);
    m.invoke(obj, parametersMethod);
}

可以这样调用:

invokeMethod("com.example.MyClass", "tryIt", "SomeString", true);

推荐阅读