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.
+7
A:
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
Jon Skeet
2010-06-17 11:33:34
+1
A:
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.
Stephen C
2010-06-17 11:56:29