Java loading resources Class.class.getResource vs

2019-06-03 14:57发布

问题:

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.

回答1:

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.



回答2:

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.