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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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 forfoo.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
回答2:
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.