英文:
NoSuchMethodException for methods using custom data type
问题
以下是您提供的代码部分的翻译:
加载的类:
public void execute(ProcessingData data){
System.out.println("进入 execute(ProcessingData data)");
}
调用的类:
URLClassLoader loader =
new URLClassLoader(new URL[] {new File(alg.getPath()).toURI().toURL()}, AlgorithmLoader.class.getClassLoader());
// 将类加载到内存中
Class<?> algClass = Class.forName(className, true, loader);
logger.logInfo("已加载类。尝试在飞机上调用 execute(data):" + data.getFlightData().getAircraftId());
Method processMethod = null;
try {
Object obj = algClass.newInstance();
processMethod = algClass.getDeclaredMethod("execute", ProcessingData.class);
processMethod.invoke(obj, data);
} catch (final NoSuchMethodException exception) {
logger.logInfo(exception.toString());
}
loader.close();
英文:
Whenever dynamically loading a class using the URLClassLoader I get a NoSuchMethodException when trying to execute a method with a custom data type as a parameter. It finds methods with standard types like String and int but not the custom type.
Loaded Class:
public void execute(ProcessingData data){
System.out.println("entered execute(ProcessingData data");
Calling Class:
URLClassLoader loader =
new URLClassLoader(new URL[] {new File(alg.getPath()).toURI().toURL()}, AlgorithmLoader.class.getClassLoader());
// Load class into memory
Class<?> algClass = Class.forName(className, true, loader);
logger.logInfo("Loaded class. Attempting to invoke execute(data) on aircraft: "+ data.getFlightData().getAircraftId());
Method processMethod = null;
try {
Object obj = algClass.newInstance();
processMethod = algClass.getDeclaredMethod("execute", ProcessingData.class);
processMethod.invoke(obj, data);
} catch (final NoSuchMethodException exception) {
logger.logInfo(exception.toString());
}
loader.close();
答案1
得分: 0
你在没有任何对象的情况下调用该方法(invoke
的空参数)。这意味着该方法将被期望为静态方法。
如果你的方法不是静态的,那么你首先需要使用getConstructors()
创建一个algClass
类型的实例,并将该对象传递给invoke
调用的第一个参数。
英文:
You're invoking the method without any object (null parameter of invoke
). This means that the method will be expected to be static.
If your method is not static then you first need to create an instance of the type algClass
using getConstructors()
and pass that object to the first parameter of the invoke
call.
答案2
得分: 0
我猜想你的UrlClassLoader加载的ProcessingData与你发布的代码中执行的代码所使用的类加载器不同。请记住,通过不同的类加载器加载的类在JVM看来是不同的类。
英文:
My guess would be that your UrlClassLoader gets ProcessingData loaded by different class loader than your executing code in the posted snippet. Recall that classes loaded via different class loaders are different classes as far as JVM is concerned.
专注分享java语言的经验与见解,让所有开发者获益!
评论