为什么将getResource或getResourceAsStream方法放置在Class.java中?

huangapple go评论68阅读模式
英文:

Why is getResource or getResourceAsStream method placed in Class.java?

问题

我看的方式是,这些方法被用于获取一个资源并返回相应的对象。那么为什么把它们放在Class.java中呢?它们并没有提供任何关于类的信息或元数据,那为什么不把它放在'class'类中,而不是IO包中呢?

英文:

The way I see it, these methods are used to fetch a resource and return the respective object. So why are they placed in Class.java? They're not providing any information or metadata about the class then why put it in 'class' class and not in IO package?

答案1

得分: 3

<sup>我只会在这里提到`getResource`,但是所有内容同样适用于`getResourceAsStream`。</sup>

这些方法涉及加载与您的类捆绑的资源,因此它们与`Class`的功能*某种程度上*相关。但确实有一个地方它们更合适。那就是`ClassLoader`。

实际上,存在一个名为[a `ClassLoader.getResource` 方法][1]的方法,它看起来与[同名的 `Class` 版本][2]非常相似。

事实上,这两种方法之间的主要区别在于,如果请求的资源名称不以`/`开头,`Class` 版本将在所请求的资源名称前添加修改后的包名称。

这意味着 `mypackage.MyClass.class.getResource("foo")`(几乎相等,但不完全相等)于 `mypackage.MyClass.class.getClassLoader().getResource("mypackage/foo")`。这使得 `Class` 版本非常适用于加载与给定类密切相关的资源(可以说是“位于同一个包中”,尽管从技术上讲不完全准确)。

  [1]: http://是的,有一个更适合此类方法的地方,就是那里
  [2]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getResource(java.lang.String)
英文:

<sup>I'll only mention getResource here, but everything equally applies to getResourceAsStream.</sup>

Those methods are about loading resources that are bundled with your classes, so they are somewhat related to what Class does. But there is indeed a place where they would fit better. And that is ClassLoader.

And in fact, there is a ClassLoader.getResource method that looks awfully similar to the Class version of the same name.

In fact the major difference between those two methods is that the Class version will prepend the modified package name to the front of the requested resource name, if it doesn't start with /.

That means that mypackage.MyClass.class.getResource(&quot;foo&quot;) is (almost, but not quite) equivalent to mypackage.MyClass.class.getClassLoader().getResource(&quot;mypackage/foo&quot;). This makes the Class version very useful to load resources that are tightly related to a given class (one could say "are in the same package", except that's not quite technically true).

huangapple
  • 本文由 发表于 2020年8月29日 03:45:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63640036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定