Constructor.newInstance 中的自定义类加载器

发布于 2024-08-09 16:33:54 字数 317 浏览 8 评论 0原文

我通过 bean 脚本框架使用 rhino 在我的 java 进程中创建和配置对象。脚本中使用的一些类需要动态加载,因为它们并不总是位于标准类路径上。

为了加载这些类,我使用自定义类加载器初始化脚本框架的上下文工厂,该加载器从辅助目录加载这些类。这效果很好。

问题是其中一些类在其构造函数中使用其他类,这些类也必须从该辅助目录加载。查看源代码,我发现 javascript 引擎只是调用 Constructor.newInstance。

我如何知道 newInstance 调用使用哪个类加载器,我可以注入自己的类加载器,以便我可以手动加载标准类加载器不知道如何加载的类。

I'm using rhino via the bean scripting framework to create and configure objects in my java process. Some of the classes used in the scripts need to be loaded dynamically as they won't always be on the standard classpath.

To load these classes I initialize the scripting framework's context factory with a custom class loader that loads these classes from an auxilary directory. This works well.

The problem is that some of these classes, in their constructors, use other classs which must also be loaded from this auxilary directory. Looking at the source I see that the javascript engine is simply calling Constructor.newInstance.

How do I know which classloader the newInstance call uses, and can I inject my own so I can manually load classes that the standard class loader doesn't know how to load.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一页 2024-08-16 16:33:54

尝试将类加载器的父类加载器设置为应用程序类加载器。

ClassLoader myLoader = new ClassLoader(getClass().getClassLoader()) { 
... your code loading from custom directory ...
}

从加载器加载的类将使用您的加载器查找其他类,因此您的加载器需要提供这些类(通过委托给父级)

Try setting the parent classloader of your class loader to the application classloader.

ClassLoader myLoader = new ClassLoader(getClass().getClassLoader()) { 
... your code loading from custom directory ...
}

The classes loaded from your loader will use your loader to lookup other classes, so your loader needs to provide those (by delegating to the parent)

赤濁 2024-08-16 16:33:54

Constructor.newInstanceConstructor 实例进行操作,该实例属于由特定 ClassLoader 加载的特定 Class 实例>。类通过它们自己的类加载器链接。

Single-arg Class.forName 使用直接调用者的类加载器(这是一个非常顽皮的 API)。

Constructor.newInstance operates upon a Constructor instance, which belongs to a particular Class instance which was loaded by a particular ClassLoader. Classes link through their own class loader.

Single-arg Class.forName uses the immediate caller's class loader (it is a very naughty API).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文