[英]How to invoke a method inside a external jar using reflection
我想通過使用反射調用在外部.jar內部的方法。
這是罐子里的示例代碼。
public class HelloFunction implements Runnable, RequestHandler<Request> {
@Override
public void handle(final Request request) {
System.out.println("handle : " + request);
}
@Override
public void run() {
System.out.println("run......");
}
}
然后,我將此jar加載到單獨的Java程序中,並嘗試調用HelloFunction.handle()方法。 這是該部分的示例代碼。
public class App {
public static void main(String[] args) {
test();
}
public static void test(){
try{
final Class<?> functionClass = getClassFromFunctionJar("com.hello.HelloFunction");
final Object functionClassObject = functionClass.newInstance();
if(functionClassObject instanceof RequestHandler){
@SuppressWarnings("unchecked")
final RequestHandler<Object> handler = RequestHandler.class.cast(functionClassObject);
final Object inputObject = getRequestClass(functionClass).newInstance();
handler.handle(inputObject);
}
}catch(final Exception e){
System.err.println(e.getMessage());
}
}
public static Class<?> getRequestClass(final Class<?> cls) throws FunctionInvokerException{
try{
final Type[] types = cls.getGenericInterfaces();
for(Type type : types){
//check RequestHandler
if(type.getTypeName().contains(RequestHandler.class.getName())){
final ParameterizedType parameterizedType = (ParameterizedType) type;
// [0]=> Request Type
final String inputClassName = parameterizedType.getActualTypeArguments()[0].getTypeName();
return getClassFromFunctionJar(inputClassName);
}
}
throw new Exception("UNABLE_TO_FIND_REQUEST_TYPE");
}catch(final Exception e){
throw new FunctionInvokerException(e);
}
}
private static Class<?> getClassFromFunctionJar(final String className) throws ClassNotFoundException, MalformedURLException{
final ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new URL("file:" + "/jar-location/hello.jar")}, App.class.getClassLoader());
return Class.forName(className, true, classLoader);
}
}
您可以在這里看到我使用getClassFromFunctionJar()方法從jar中加載Class。 getRequestClass()方法用於查找HelloFunction.handle()方法的輸入參數的類類型。 在調用handle()方法之前,一切都很好。
最后,我得到一個錯誤,提示“ com.hello.Request無法轉換為com.hello.Request”。 您能幫我解決這個問題嗎?
由不同的類加載器加載的相同的類定義被JVM視為兩個不同的類。
您的代碼“ URLClassLoader.newInstance”,同時獲取其他類加載器
第一個(handler#parameter)是:URLClassLoader#1&com.hello.Request
第二個(inputObject)是:URLClassLoader#2&com.hello.Request
“無法將com.hello.Request強制轉換為com.hello.Request”。
實際錯誤是
“ URLClassLoader#2 com.hello.Request無法轉換為URLClassLoader#1 com.hello.Request”
並提出以下建議:
private static final ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new URL("file:" + "/jar-location/hello.jar")}, App.class.getClassLoader());
private static Class<?> getClassFromFunctionJar(final String className) throws ClassNotFoundException, MalformedURLException{
return Class.forName(className, true, classLoader);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.