Java – how to get resources in another jar
I have a jar embedded in a package. I need to obtain the resources packaged with it, as shown below:
MyBundle -\ src -\lib -\MyEmbeddedJar -\src -\SomeClass -\someResource.xml
I tried to access' someresource 'from' someclass' XML ', as follows:
SomeClass.class.getResource( "someResource.xml" );
But I had no luck I've tried to attach several variants of CWD (e.g.'. / someresource. XML '), but I can't load this resource
I know that the "correct" method is to use activator to get the correct classloader, but embedded jar can be used in other projects, so I don't want to add OSGi specific code to play well with OSGi in order to get it
Is there any other way to load resources in OSGi?
Solution
I assume that someclass is located in an embedded jar (for example, somejar. Jar) and someresource XML is located in the external jar and in the Lib directory
In this case, this cannot be done in a non - OSGi context Let's look at these two cases in isolation
In OSGi
Someresource can be accessed well using a regular (non OSGi specific) resource loading mechanism XML, provided it can be accessed from bundle classpath For example, if you have the following list title,
Bundle-ClassPath: .,somejar.jar
You will be able to access your resources using "lib / someresource. XML" Note the point on the classpath: this means that you can get classes and resources from the root directory of the jar If you forget this, you will only be able to access somejar Jar
Do not use OSGi
If you don't use OSGi, there is no (fairly simple) way to get the classes and resources in the internal jar I know
Your choice
Depending on how you want the bundle to look, you now have two options
>Is someclass really necessary in embedded jars? If so, you will feel at a loss, and your jar will only use OSGi. > If you can choose to add somejar Unpacking jar into your jar can solve the problem, and your jar can work normally in both cases
Personally, I will choose option 2: unless you have resources, they may overwrite each other when you 'merge' cans, so there is no problem to have a little resources in your bag