简体   繁体   English

java访问另一个类加载器加载的类中的资源文件

[英]java access resource files from class loaded by another classloader

I have a class which needs to do some https request. 我有一堂课,需要做一些https请求。
Just in case the ssl truststore and keystore are not set, the jar which contains my class, has them in its resource folder. 以防万一未设置ssl信任库和密钥库,包含我的类的jar将其放在其资源文件夹中。
My class is being dynamically loaded by some classloader I have no control about and now when I do 我的班级正在由我无法控制的某个类加载器动态加载,现在当我执行

getClass().getClassLoader().getResourceAsStream("keystore.jks");

the resource is not being found. 找不到资源。
My theory on this is that getClassLoader returns the classloader returns the classloader from a webserver, which probably isn't able to find the resource keystore.jks in the jar file. 我的理论是, getClassLoader返回类加载器,从Web服务器返回类加载器,这可能无法在jar文件中找到资源keystore.jks
Any help is appreciated. 任何帮助表示赞赏。

I found a way around the problem. 我找到了解决问题的方法。 I can use MyClass.class.getResourceAsStream("/keystore.jks"); 我可以使用MyClass.class.getResourceAsStream("/keystore.jks"); to load the resource properly. 正确加载资源。
I am not exactly sure why it works though. 我不确定为什么会起作用。 When I was using MyClass.class.getClassLoader().getResourceAsStream("keystore.jks"); 当我使用MyClass.class.getClassLoader().getResourceAsStream("keystore.jks"); it wasn't working. 它没有用。 Although I think I read somewhere that Class.getResource() with a leading / is the same as ClassLoader.getResource() without one. 尽管我认为我在某处读到带有前导/ Class.getResource()与没有一个的ClassLoader.getResource()相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM