Java加载资源Class.class.getResource与< classname> .class.getResource [英] Java loading resources Class.class.getResource vs <classname>.class.getResource

查看:66
本文介绍了Java加载资源Class.class.getResource与< classname> .class.getResource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别?

What is the difference between the two ?

我的资源文件打包在根级别包中。在我测试的特定情况下,调用Class.class.getResource( / rec.txt)似乎可以正常工作。但是,当我尝试使用此jar作为较大环境中的依赖项(hadoop)时,此方法不起作用(返回null)。但是,将类更改为代码中的任何特定类都可以修复该问题。有人可以给我一些光。

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.

推荐答案

发生这种情况的原因是getResource的工作方式。本质上,它将调用委托给< classname> 的classLoader。

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.

类对象可能是由企业应用程序中的引导类加载器加载的,而您的类< classname> 是由其他类加载器加载的。

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

这篇关于Java加载资源Class.class.getResource与&lt; classname&gt; .class.getResource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆