[英]Passing Parameters Between ClassLoaders Via Reflection API
I'm using a custom Classloader to create and return an instance of a class, this seems to work ok however when I try to call a method (via the Reflection API) and pass in a custom object as described below I get a NoSuchMethodException
: 我正在使用自定义类加载器来创建和返回类的实例,这似乎工作正常但是当我尝试调用方法(通过Reflection API)并传入自定义对象时,如下所述,我得到一个
NoSuchMethodException
:
Supposing that the custom class loader creates and returns an instance like so: 假设自定义类加载器创建并返回如下所示的实例:
Object obj = customClassLoader.load(String className,Class[] paramTypes,Object[] param)
Then I call a method (via reflection) and pass in a custom object: 然后我调用一个方法(通过反射)并传入一个自定义对象:
NOTE: THIS IS THE LINE CAUSING THE ERROR 注意:这就是造成错误的因素
Method m = obj.getClass.getDeclaredMethod("mName",new Class[]{aCustomObject.class})
m.invoke(obj,new Object[]{new CustomObject() })
I'm stumped as to what could be causing the exception since a method definitely does exist which takes the specified custom object, I have confirmed this by using reflection to list all methods. 我很难理解可能导致异常的原因,因为确实存在一个接受指定自定义对象的方法,我通过使用反射来列出所有方法来证实这一点。
How is your custom loader's load() method instantiating the object it is to return? 你的自定义加载器的load()方法如何实例化它要返回的对象? Maybe the
NoSuchMethodException
arises during trying to find the correct constructor? 在尝试查找正确的构造函数时,可能会出现
NoSuchMethodException
?
This example seems to work out OK: 这个例子似乎没问题:
package com.pholser;
import java.lang.reflect.Method;
public class ClassLoading {
public static class CustomLoader extends ClassLoader {
public Object load(String className, Class<?>[] paramTypes, Object[] params) throws Exception {
Class<?> loaded = loadClass(className);
return loaded.getConstructor(paramTypes).newInstance(params);
}
}
public static class ACustomObject {
}
public void foo(ACustomObject a) {
System.out.println("foo");
}
public static Object newCustomObject() throws Exception {
return new CustomLoader().load("com.pholser.ClassLoading$ACustomObject", new Class<?>[0], new Object[0]);
}
public static void main(String[] args) throws Exception {
ClassLoading obj = new ClassLoading();
Method m = obj.getClass().getDeclaredMethod("foo", ACustomObject.class);
m.invoke(obj, newCustomObject());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.