使用URLClassLoader调用外部jar,并执行指定类方法
程序员文章站
2022-05-04 18:17:55
...
/**
* 加载jar,并得到指定的类
*
* @param jarFileName
* @param classFullName
* @return
* @throws MalformedURLException
*/
private Class loadClass(String jarFileName, String classFullName)
throws MalformedURLException {
//要使用URLClassLoader,因为不是同工程下,同工程下可使用ClassLoader
URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(
jarFileName) });
JarFile jarFile = null;
Class c = null;
try {
jarFile = new JarFile(jarFileName.substring(5));
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<JarEntry> en = jarFile.entries();
while (en.hasMoreElements()) {
JarEntry je = en.nextElement();
String name = je.getName();
String s5 = name.replace('/', '.');
if (s5.lastIndexOf(".class") > 0) {
String className = je
.getName()
.substring(0, je.getName().length() - ".class".length())
.replace('/', '.');
if (classFullName.equals(className)) {
try {
c = classLoader.loadClass(className);
System.out.println(className);
} catch (ClassNotFoundException e) {
System.out.println("NO CLASS: " + className);
} catch (NoClassDefFoundError e) {
System.out.println("NO CLASS: " + className);
}
break;
}
}
}
return c;
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Class clazz = this.loadClass("file:C:" + File.separator + "Main.jar",
"com.test.Main");
System.out.println("开始执行!");
// com.test.Main类中的二个方法,为了测试返回值写死,可以得到类中的方法集合
String[] me_name = new String[] { "main", "a" };
for (int i = 0; i < me_name.length; i++) {
try {
Method me = clazz.getMethod(me_name[i],
new Class[] { new String[] {}.getClass() });
// 方法的返回值,可以给方法加参数
Object object = me.invoke(clazz.newInstance(), new Object[] { new String[] { "111111111" } });
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("开始js!");
}
上一篇: java 多线程“同步锁”
下一篇: java 线程学习笔记(一)