java - 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
.
解决方案
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);
推荐阅读
- python - 作为 Python 3.8 安装的一部分消失的 pip
- sql - 使用此 SQL 语句在 Oracle 中获取单个随机行的分布是什么?
- go - go.mod 中的 golang.org/x/sys@hash 版本被忽略
- python - 将置信区间对齐一个低于另一个
- c++ - C++ ifstream 问题。我想从 .csv 文件中读取“坐标”,但不知何故,代码会两次读取文件并放入奇怪的数字
- javascript - React-Native 如何实现暗模式?
- python - 如何删除文件中某行之后的所有行我python
- c++ - 无法使用 clang 预构建的二进制文件构建 cpp:找不到文件 wchar.h
- reactjs - 具有相同数据的两个组件,但我不明白为什么 reactJs
- php - 使用时我的数据库查询不起作用?在声明中