我正在编写一个动态加载jar文件的应用程序并在jar文件中执行该类。 我能够加载jar文件并获取方法。但是当我调用该方法时,我没有执行该方法,但没有例外。
我尝试执行的方法是公开的。
URLClassLoader urlClassLoader;
//no paramater
Class noparams[] = {};
try {
urlClassLoader = new URLClassLoader(new URL[]{new URL("file:///C:/Users/jamju02/Desktop/today/jar2.jar")});
Class pluiginClass = urlClassLoader.loadClass("plugintest.PluginTest");
// Create a new instance from the loaded class
Constructor<?> constructor = pluiginClass.getConstructor();
Object classobject = constructor.newInstance();
System.out.println(classobject.getClass().getName());
//Method method = pluiginClass.getMethod("getName");
Method[] m = pluiginClass.getDeclaredMethods();
for (int i = 0; i < m.length; i++){
System.out.println(m[i].toString());
m[i].setAccessible(true);
m[i].invoke(classobject, null);
}
// method.invoke(object);
//call the printIt method
Method method = pluiginClass.getDeclaredMethod("getName", noparams);
method.setAccessible(true);
method.invoke(classobject);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
package plugintest;
public class PluginTest implements SimplePlugin {
public String getName() {
return "I'm the plugin!";
}
}
它打印类名和方法名,但不执行该方法。
答案 0 :(得分:1)
try块中的最后一行需要更改为:
System.err.println((String) method.invoke(classobject));