1

I am trying to load a resource into my runtime for a library. But in my current implementation only the very specific instance of the URLClassLoader can see it.

URLClassLoader classLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
classLoader.addFile(super.getResource(urlPath));

classLoader.classLoader.getResourceAsStream(path) //works

URLClassLoader secondClassLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
secondClassLoader.classLoader.getResourceAsStream(path) // doesn't work 

Another problem is, that I don't know which ClassLoader the library actually uses as parent. The best solution would be one where every class loader can access the resource.

How to make sure that the dynamically loaded resource is accessible by all the classloaders?

code
  • 2,283
  • 2
  • 19
  • 27
Philipp
  • 11
  • 4
  • There seems to be something wrong with your code - why do you access a `classLoader` property of `classLoader` and `secondClassLoader`? – schneida May 14 '18 at 13:13
  • Just to show where my problem lies. I want my resource to be available to every single class loader since I can't change the library. – Philipp May 14 '18 at 15:47
  • Hmm I still don't understand. The code you posted won't compile, so of course it doesn't work. In general to have your resources available to every single class loader you have to have them in the system classloader or even the bootstrap classloader. Afaik you can do that via reflection only: See e.g here: https://stackoverflow.com/a/60766/606513 A better approach would be to create your own classloader and also load your library through this classloader. That way the library will share the same classpath as your injected libs and thus they will "see" each other. – schneida May 15 '18 at 08:48

1 Answers1

0

It looks like, you have two options(though both solutions work on a similar principle).

General solution(No custom classloaders): Load the resource from your application classloader. This can be achieved by making sure that the resource location is included in your application classpath(saving the resource as part of application jar file is one way to achieve this).

A bit complicated one(With custom classloaders): In this scenario, you have to make sure that the resource path is added to classpath of all of the custom classloaders. Easier and cleaner approach would be to define a super custom-classloader and inherit all the other classloaders from this super loader. And load the resource into classpath of the super classloader.

By now, I hope you got the idea of underlying principle: Classloaders will be able to load a given resource if it is visible in their parent's classpaths(recursively) or in their own classpaths.

code
  • 2,283
  • 2
  • 19
  • 27