Java loading resources Class.class.getResource vs <classname>.class.getResource

你说的曾经没有我的故事 提交于 2019-12-08 07:46:55

问题


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.



来源:https://stackoverflow.com/questions/6823597/java-loading-resources-class-class-getresource-vs-classname-class-getresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!