我正在尝试从 jar 文件中的类动态执行函数。我有 jar 文件的位置、类的名称和其中的函数作为字符串。
这是我到目前为止所得到的:在主程序中:
public class Main
{
public static void main(String[] args)
{
File file = new File("E:\\DeSKtop\\hw.jar");
String lcStr = "Main1";
URL jarfile;
try {
jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Method method = loadedClass.getDeclaredMethod("returnHW");
Object instance = loadedClass.newInstance();
Object result = method.invoke(instance);
//System.out.println(method.invoke());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(loadLibrary(myJar));
catch (ClassNotFoundException 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 (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException 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();
}
}
你能告诉我我做错了什么吗?先感谢您。
缥缈止盈
相关分类