类加载器的资源路径总是绝对的吗? [英] Classloader resource paths are always absolute?

查看:109
本文介绍了类加载器的资源路径总是绝对的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jon Skeet在关于类加载方法之间差异的流行答案中,

In a popular answer regarding the difference between class loading methods, Jon Skeet has stated,


Classloader资源路径始终被认为是绝对的。

Classloader resource paths are always deemed to be absolute.

甚至更受欢迎的 answer 举例说明了这一说法。

An even more popular answer affirms this statement with an example.


ClassLoader.getResourceAsStream(path)将所有路径视为
绝对路径。因此,调用
String.getClassLoader()。getResourceAsString( myfile.txt)
String.getClassLoader()。 getResourceAsString( / myfile.txt)都将
在类路径中的以下位置查找文件:
./ myfile.txt

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.getClassLoader().getResourceAsString("myfile.txt") and String.getClassLoader().getResourceAsString("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

不管示例无法编译,共识表明前导斜杠与

Disregarding the fact that the example won't compile, consensus indicates a leading forward slash is irrelevant to the ClassLoader.

一个简单的测试显示否则。

A simple test shows otherwise.

Foo.class.getClassLoader ().getResource( test.xml)//文件

Foo.class.getClassLoader()。getResource( / test.xml )// null

我只是添加了路径 files / test.xml 到测试项目的类路径,其中名为 Foo 的类包含一个 main()方法,打印出结果这两个电话中的一个。自数百人投票赞成上述答案以来,我缺少什么? ClassLoader是绝对的,还是取决于输入名称的结构?

I have simply added the path files/test.xml to the classpath of a test project, with a class named Foo containing a main() method printing out the results of those two calls. What am I missing, since hundreds of people have up-voted the aforementioned answers? Are ClassLoaders absolute, or do they depend on the structure of the input name?

Oracle博客帖子对我的理解很有帮助。

This Oracle blog post was helpful to my understanding.

最终根据资源名称构造URL的方法是 URLClassPath.JarLoader.checkResource()

The method which ultimately constructs a URL from the resource name is URLClassPath.JarLoader.checkResource().

推荐答案

显然不是。

由类加载器解释 getResource(name)<中的 name / code>。

It is up to the class loader to interpret name in getResource(name).

检查 URLClassLoader 的源代码,最终它调用了

Examining the source code of URLClassLoader, eventually it calls

新URL(baseURL,名称)

在这里很重要名称是绝对的还是相对的

It is important here whether name is absolute or relative

对于某些 baseURL,

It is possible that, for some baseURL, absolute /foo/bar and relative foo/bar have the same effect. In particular, this is always the case for "jar file URL" in classpaths

baseURL:       jar:file:/home/duke/duke.jar!/

 foo/bar  ->   jar:file:/home/duke/duke.jar!/foo/bar 
/foo/bar  ->   jar:file:/home/duke/duke.jar!/foo/bar 

这篇关于类加载器的资源路径总是绝对的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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