开发者

Why getResourceAsStream method is in Class class?

开发者 https://www.devze.com 2023-01-04 00:09 出处:网络
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 s开发者_开发百科

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 s开发者_开发百科tatic method and it can be in any class.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消