如何在 Tomcat Web 应用程序中从外部 jar 中获取类实例

发布于 2025-01-15 04:21:39 字数 763 浏览 2 评论 0原文

基本上,如果人们想为我们生成的文件定义自己的存储库,我们的代码允许人们传入 IRepository 接口的自定义实现。我不断收到以下错误:

ClassCastException: S3RepositoryPlugin.S3Repository cannot be cast to package_name.IRepository

这就是我定义 S3Repository 的方式:

public class S3Repository implements IRepository 

这就是我试图满足它的方式:

URL[] urls = { new URL("jar:file:" + assembly +"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
Class classToLoad = Class.forName(className, true, cl);
IRepository externalRepo = (IRepository) classToLoad.newInstance();

其中 assembly 是 jar 的完整路径,className 是“S3RepositoryPlugin.S3Repository”。

知道为什么会发生这种情况吗?从我在网上看到的内容来看,转换到接口的工作方式似乎与转换到类不同,但我不确定我使用的代码是否一定会受到影响。

笔记: 使用Tomcat9和java8

Basically our code allows people to pass in a custom implementation of our IRepository interface if they want to define their own repository for the files we generate. I keep getting the following error:

ClassCastException: S3RepositoryPlugin.S3Repository cannot be cast to package_name.IRepository

This is how I define the S3Repository:

public class S3Repository implements IRepository 

And this is how im trying to insatiate it:

URL[] urls = { new URL("jar:file:" + assembly +"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
Class classToLoad = Class.forName(className, true, cl);
IRepository externalRepo = (IRepository) classToLoad.newInstance();

Where assembly is the full path to the jar, and className is "S3RepositoryPlugin.S3Repository".

Any idea as to why this is happening? From the stuff Im seeing online it seems casting to interfaces works differently than casting to classes but im not sure if the code im using is necessarily affected by that.

NOTE:
Using Tomcat9 and java8

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

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

发布评论

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

评论(1

陌伤ぢ 2025-01-22 04:21:39

我必须将以下代码添加到 URLClassLoader 才能使其工作:

URLClassLoader cl = URLClassLoader.newInstance(urls, getClass.getClassLoader());

I had to add the following code to the URLClassLoader to make it work:

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