为什么 getResourceAsStream 方法在 Class 类中?
为什么 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与类有关系:
getResourceAsStream("baz.txt")
foo.bar.SomeClass
它将查找/foo/bar/baz.txt
There is a relationship to the class:
getResourceAsStream("baz.txt")
on the class forfoo.bar.SomeClass
it will look for/foo/bar/baz.txt
不正确。并非所有类加载器都从常规 JAR 文件加载资源。
在这种情况下,当您通过
Class
使用ClassLoader
API 时,所有这些复杂性都对您隐藏起来。不正确。请参阅@Jon Skeet 的回答。请注意,调用 Class.getResourceAsStream(String) 会提供与该类属于同一安全上下文的资源。如果使用多个类加载器/安全上下文,这一点可能非常重要。
Incorrect. Not all classloaders load resources from regular JAR file.
All of this complexity is hidden from you when you use the
ClassLoader
API viaClass
in this case.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.