Java动态加载JAR文件

jues 提交于 2019/03/14 - 15:00 周四
内容
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import jar.Test1;

public class demo {

	public static void main(String[] args) {
		Test1 t1 = null;
		Test1 t2 = null;
		try {
			t1 = (Test1) demo
					.loadClass("E:\\workspace\\project\\tmp\\LoadJarDemo\\LoadJarDemo1.jar", "jar.PrintTest1")
					.newInstance();
			t2 = (Test1) demo
					.loadClass("E:\\workspace\\project\\tmp\\LoadJarDemo\\LoadJarDemo2.jar", "jar.PrintTest1")
					.newInstance();
		} catch (Exception e) {
			return;
		}

		t1.print();
		t2.print();
	}

	//
	static public Class<?> loadClass(String filename, String classname) {
		try {
			File file = new File(filename);
			URL url = file.toURI().toURL();
			@SuppressWarnings("resource")
			URLClassLoader loader = new URLClassLoader(new URL[] { url });
			//
			return loader.loadClass(classname);
		} catch (Exception e) {
			return null;
		}
	}

}

 

评论

添加新评论

此字段内容将保密,不会被其他人看见。