Java 从Jar文件中动态加载类

由于开发的需要,需要根据配置动态加载类,所以简单测试了一下JAVA动态加载类

定义接口

package loader;

public interface HelloIface {

    public String hello();
    
    public String sayHi(String name);

}

实现接口

在其他插件类实现此接口,并导出为jar,如D:/tmp/test.jar

package loader;

public class HelloImpl implements HelloIface{

	@Override
	public String hello() {
		return "hello,JAVA世界";
	}

	@Override
	public String sayHi() {
		return "Hi,JAVA World " + name;
	}
}

动态加载类

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class LoadJar {
	public static void main(String[] args) {
		String classPath = "loader.HelloImpl";// Jar中的所需要加载的类的类名
		String jarPath = "file:///D:/tmp/test.jar";// jar所在的文件的URL

		loadJar1(classPath, jarPath);
		loadClass(classPath);
		loadJar2(classPath, jarPath);
		loadClass(classPath);
	}

	public static void loadJar1(String classPath, String jarPath) {
		ClassLoader cl;
		try {
			// 从Jar文件得到一个Class加载器
			cl = new URLClassLoader(new URL[] { new URL(jarPath) });
			// 从加载器中加载Class
			Class<?> c = cl.loadClass(classPath);
			// 从Class中实例出一个对象
			HelloIface impl = (HelloIface) c.newInstance();
			// 调用Jar中的类方法
			System.out.println(impl.hello());
			System.out.println(impl.sayHi("zhangsan"));
			
			try {
				HelloIface impl2 = (HelloIface) Class.forName(classPath)
						.newInstance();
				System.out.println(impl2.hello());
			} catch (ClassNotFoundException e) {
				System.out.println("非系统加载器加载的JAR,不能通过Class.forName使用");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void loadJar2(String classPath, String jarPath) {
		URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		Class<URLClassLoader> sysClass = URLClassLoader.class;
		try {
			//改变方法的可见性(即通过反映访问本来不可以访问的方法)
			Method method = sysClass.getDeclaredMethod("addURL"new Class[] { URL.class });
			method.setAccessible(true);
			method.invoke(urlLoader, new URL(jarPath));
			
			Class<?> objClass = urlLoader.loadClass(classPath);
			Object instance = objClass.newInstance();
			Method method2 = objClass.getDeclaredMethod("sayHi"new Class[]{ String.class});
			System.out.println(method2.invoke(instance, "zhangsan"));
			
			HelloIface impl2 = (HelloIface) Class.forName(classPath).newInstance();
			System.out.println(impl2.hello());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void loadClass(String classPath){
		try {
			HelloIface impl2 = (HelloIface) Class.forName(classPath)
					.newInstance();
			System.out.println(impl2.hello());
		} catch (Exception e) {
			System.out.println("非系统加载器加载的JAR,不能通过Class.forName使用");
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值