Java loading resources Class.class.getResource vs <classname>.class.getResource
Asked Answered
R

2

1

What is the difference between the two ?

my resource files are packaged in the root level package. And calling Class.class.getResource("/rec.txt") seemed to work in the specific case I tested. But, when I tried to use this jar as a dependency in a larger environment ( hadoop ) this didnt work ( returned null ). But, changing "Class" to any specific class in the code fixed it. Could someone throw some light.

Rodrick answered 25/7, 2011 at 23:23 Comment(0)
B
3

The reason this is happening is that the way getResource works. It essentially delegates the call to the classLoader of the <classname> as put it in your question.

The Class object was probably loaded by the bootstrap classloader in an enterprise application whereas your class <classname> was loaded by a different classloader.

Blakey answered 25/7, 2011 at 23:37 Comment(3)
Ah I see. Is there anything that i can log to verify this. Or is there something i can look for in the source ?Rodrick
Could you explain a little more as to how this could affect the availability of resources in the classpath.Rodrick
@Rodrick -- sorry for the late response. You can refer to the ClassLoader api .. what will help is to print the URL of the classloader.getResource(yourclass) to help isolate your problem.Blakey
S
0

Class.getResource() resolves relative paths by appending it to the path of the class on which you called getResource(). A path is relative unless it begins with a "/", in which case it's resolved against the root of the classpath. ClassLoader.getResource() resolves all paths as absolute, but you mustn't prepend a "/" to the path. That's all there is to it, really. If either method returns null, it means the resource doesn't exist.

Edit: Oh, I'm sorry. I didn't read your question carefully enough and missed the Class vs. class part. The distinction you're looking for is that loading a resource via a class delegates to its associated ClassLoader. I don't know much about how Hadoop sets up its ClassLoaders, but the java.lang.Class class will have been loaded by the bootstrap ClassLoader, and almost certainly, the bootstrap ClassLoader doesn't have any of your jars on its classpath, so it would fail to find any resources defined therein. Your own class, however, would have to be loaded by a ClassLoader that has access to your jars, and thus would be able to load your resource.

Sepaloid answered 25/7, 2011 at 23:34 Comment(2)
I know that. If you notice carefully , there is really no ClassLoader here.Rodrick
@smartnut: There's always a ClassLoader. Updated my answer.Sepaloid

© 2022 - 2024 — McMap. All rights reserved.