1

Don't flag as duplicate yet!

Hear me out; all of the solutions that I have seen are good, but I don't understand how the class paths work when loading resources using:

ClassLoader classLoader = getClass().getClassLoader()

I want to set up a resource loader (named ResourceLoader) that can load from anywhere within the jar package.

So if the loader is placed in com.spikespaz.engine.loader.ResourceLoader, I don't want to be stuck in the relative path of com.spikespaz.engine.loader.

I want to be able to load from com.spikespaz.game.resources.textures and com.spikespaz.game.resources.models without the need to put a reader in the parent directory.

What I found is this: https://stackoverflow.com/a/3862115/2512078

But from what I understood, all of those options in his answer must be relative to the class loading them. (getClass()) Is there a way around this, or am I misunderstanding it?

If I am misunderstanding it, could someone explain better?

Any solutions must be relative to the exact root of the jar package or source of the development environment, and I must not need to put anything in that root.

Thanks.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49

1 Answers1

2

I think you misunderstood or misread his answer https://stackoverflow.com/a/3862115/2512078

Both the normal classloader and the context classloader are able to load resources with an absolute path.

To do this using the normal classloader, make sure the resource path has a leading / in front of it, otherwise it loads the resource relative to the package of the class loading it.

this.getClass().getResource("/foo/bar.txt")` 

The context classloader is never loading resources relative to a class, paths are always interpreted as absolute paths.

Thread.currentThread().getContextClassLoader().getResource("foo/bar.txt")

Note: Do not use a leading slash with the context classloader.

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
  • It looks good by the way if your wondering why I haven't accepted the answer. I will, once I have a chance to test it. I'm currently re-writing the rest of my code so it might be a bit. – Jacob Birkett Jul 05 '17 at 15:42
  • Why exactly do you say not to use a leading slash with the context classloader? – Garret Wilson Nov 01 '20 at 21:29
  • Actually I'm discovering that at least some non-context class class loaders won't work with a leading slash at all, so it seems like https://stackoverflow.com/q/32215693 is correct. – Garret Wilson Nov 01 '20 at 22:05