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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Why exactly do you say not to use a leading slash with the context classloader?
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 stackoverflow.com/q/32215693 is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.