问题描述
为什么在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 jars 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(myJar.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);
痛苦,但确实如此。
这篇关于我应该如何在运行时动态加载Jars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!