gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:18:24 24 4
gpt4 key购买 nike

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

最奇怪的事情是,如果我打印方法名称及其参数,与我使用的相同,但我总是得到: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)

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

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

最佳答案

allMethods 的类型为 Method[],它没有方法 tryIt(String, boolean)。您想要在 cls

上调用 getMethod()

此外,您调用的方法是错误的,因为 Method.invoke() 需要一个参数数组而不是 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);

关于java.lang.NoSuchMethodException : [Ljava. lang.reflect.Method;.myMethod(java.lang.String, boolean 值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54518462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com