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

查看:34
本文介绍了如何在运行时动态加载 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天全站免登陆