如何在 Tomcat Web 应用程序中从外部 jar 中获取类实例
基本上,如果人们想为我们生成的文件定义自己的存储库,我们的代码允许人们传入 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我必须将以下代码添加到 URLClassLoader 才能使其工作:
I had to add the following code to the URLClassLoader to make it work: