为什么 getResourceAsStream 方法在 Class 类中?

发布于 2024-09-05 21:18:39 字数 125 浏览 0 评论 0原文

为什么 public InputStream getResourceAsStream(String name) 位于 Class 类中?它只是给出jar文件中文件的输入流,与Class类没有关系。所以它可以是静态方法,也可以在任何类中。

Why public InputStream getResourceAsStream(String name) is in Class class? It just give inputstream of file which is in jar file and there is no relation with Class class. so it can be static method and it can be in any class.

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

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

发布评论

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

评论(2

油饼 2024-09-12 21:18:39

与类有关系:

  • 考虑类的包 - 如果您在类上调用 getResourceAsStream("baz.txt") foo.bar.SomeClass 它将查找 /foo/bar/baz.txt
  • 考虑类加载器来首先查找资源 - 如果它是静态方法,它如何知道要查找哪些 jar 文件(等)?生命不仅仅是系统类加载器

There is a relationship to the class:

  • The package of the class is taken into account - if you give call getResourceAsStream("baz.txt") on the class for foo.bar.SomeClass it will look for /foo/bar/baz.txt
  • The classloader is taken into account to find the resources in the first place - if it were a static method, how would it know which jar files (etc) to look in? There's more to life than the system classloader
淡写薰衣草的香 2024-09-12 21:18:39

它只是提供 jar 文件中文件的输入流...

不正确。并非所有类加载器都从常规 JAR 文件加载资源。

  • 一些类加载器从目录加载。
  • 一些类加载器从网络加载。
  • 一些类加载器从多个源加载。

在这种情况下,当您通过 Class 使用 ClassLoader API 时,所有这些复杂性都对您隐藏起来。

...与Class类没有关系。

不正确。请参阅@Jon Skeet 的回答。请注意,调用 Class.getResourceAsStream(String) 会提供与该类属于同一安全上下文的资源。如果使用多个类加载器/安全上下文,这一点可能非常重要。

It just give inputstream of file which is in jar file ...

Incorrect. Not all classloaders load resources from regular JAR file.

  • Some classloaders load from directories.
  • Some classloaders load from the network.
  • Some classloaders load from multiple sources.

All of this complexity is hidden from you when you use the ClassLoader API via Class in this case.

... and there is no relation with Class class.

Incorrect. See @Jon Skeet's answer. Note that calling Class.getResourceAsStream(String) gives a resource that belongs to the same security context as the class. This can be very important if there are multiple classloaders / security contexts in use.

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