再编写Java应用程序的时候我们通常需要动态的加载jar,具体的代码如下:
demo1.jar中的invoke方法:
package com.amx.test;
public class Test {
public String invoke(String name) {
return "您好:"+name+",欢迎访问demo1!";
}
}
demo2.jar中的invoke方法:
package com.amx.test;
public class Test {
public String invoke(String name) {
return "您好:"+name+",欢迎访问demo2!";
}
}
这两个项目都打包成jar,然后我们再另外一个程序中调用:
public class Invoke {
private static int flag = 0;
private static String softPath;
@SuppressWarnings({ "unchecked", "resource", "rawtypes" })
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
flag = scanner.nextInt();
if (flag == 0) {
softPath = "file:C:/Users/amxing/Desktop/demo1.jar";
} else {
softPath = "file:C:/Users/amxing/Desktop/demo2.jar";
}
URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL(softPath)},Thread.currentThread().getContextClassLoader());
Class demo = classLoader.loadClass("com.amx.test.Test");
Object object = demo.newInstance();
System.out.println(demo.getMethod("invoke",String.class).invoke(object,new Object[]{"amx"}));
}
}
执行结果如下:
这样就是先了动态调用jar
---------------------
版权声明:本文为CSDN博主「一直在梦想路上」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:/qq_24689783/article/details/79060488