Java加载资源 Class.class.getResource 与.class.getResource

发布于 2024-11-25 22:50:24 字数 187 浏览 2 评论 0原文

两者有什么区别?

我的资源文件是打包在根级包中的。调用 Class.class.getResource("/rec.txt") 似乎在我测试的特定情况下有效。但是,当我尝试在更大的环境(hadoop)中使用这个jar作为依赖项时,这不起作用(返回null)。但是,将“Class”更改为代码中的任何特定类即可修复此问题。有人可以提供一些线索吗?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瀞厅☆埖开 2024-12-02 22:50:28

Class.getResource () 通过将相对路径附加到您调用 getResource() 的类的路径来解析相对路径。路径是相对的,除非它以“/”开头,在这种情况下,它将根据类路径的根进行解析。 ClassLoader.getResource () 将所有路径解析为绝对路径,但不得在路径前添加“/”。真的,这就是全部。如果任一方法返回 null,则表示该资源不存在。

编辑:哦,对不起。我没有仔细阅读你的问题,错过了班级与班级的部分。您正在寻找的区别是通过类委托加载资源到其关联的 ClassLoader。我不太了解 Hadoop 如何设置其 ClassLoader,但 java.lang.Class 类将由引导类加载器加载,并且几乎可以肯定,引导类加载器的类路径上没有任何 jars,因此它将无法找到其中定义的任何资源。然而,您自己的类必须由有权访问您的 jar 的 ClassLoader 加载,从而能够加载您的资源。

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.

拥有 2024-12-02 22:50:27

发生这种情况的原因是 getResource 的工作方式。它本质上将调用委托给 的 classLoader,正如您在问题中所说的那样。

Class 对象可能是由企业应用程序中的引导类加载器加载的,而您的类 是由不同的类加载器加载的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文