如何在运行时动态加载JAR文件? [英] How to load JAR files dynamically at Runtime?

查看:374
本文介绍了如何在运行时动态加载JAR文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Java中很难做到这一点?如果要使用任何类型的模块系统,则需要能够动态加载JAR文件.有人告诉我,有一种方法可以通过编写自己的ClassLoader来完成,但是对于(至少在我看来)应该像调用带有JAR文件作为其参数的方法一样容易的事情来说,这是很多工作.

Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own ClassLoader, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.

有任何建议这样做的简单代码吗?

Any suggestions for simple code that does this?

推荐答案

之所以困难,是因为安全性.类加载器是不可变的.您不应在运行时随意向其添加类.实际上,我很惊讶能与系统类加载器一起使用.这是制作自己的子类加载器的方法:

The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader:

URLClassLoader child = new URLClassLoader(
        new URL[] {myJar.toURI().toURL()},
        this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);

痛苦,但确实如此.

这篇关于如何在运行时动态加载JAR文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆