- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Resource gathering
Sun, 2012-02-12, 20:55
Can anyone explain what's going on here? Why I can't get the resource
from the system class loader, what object is "getClass" being called
on, and why does it work from there?
scala> val sysClassLoader = java.lang.ClassLoader.getSystemClassLoader()
sysClassLoader: ClassLoader = sun.misc.Launcher$AppClassLoader@138d107f
scala> sysClassLoader.getResourceAsStream("/org/specs2/Specification.html")
res0: java.io.InputStream = null
scala> getClass().getResourceAsStream("/org/specs2/Specification.html")
res1: java.io.InputStream =
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@b37d0cf
Mon, 2012-02-13, 16:51
#2
Re: Resource gathering
Hi Daniel,
Class#getResourceAsStream allows the resource path which start with "/" but
ClassLoader#getResourceAsStream does not take "/" as the prefix of the
resource path.
So you can get the resource by following code:
sysClassLoader.getResourceAsStream("org/specs2/Specification.html")
2012/2/13 Daniel Sobral :
> Can anyone explain what's going on here? Why I can't get the resource
> from the system class loader, what object is "getClass" being called
> on, and why does it work from there?
>
> scala> val sysClassLoader = java.lang.ClassLoader.getSystemClassLoader()
> sysClassLoader: ClassLoader = sun.misc.Launcher$AppClassLoader@138d107f
>
> scala> sysClassLoader.getResourceAsStream("/org/specs2/Specification.html")
> res0: java.io.InputStream = null
>
> scala> getClass().getResourceAsStream("/org/specs2/Specification.html")
> res1: java.io.InputStream =
> sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@b37d0cf
>
> --
> Daniel C. Sobral
>
> I travel to the future all the time.
It's not easy to answer this without knowing your configuration. But
as a practical matter, someObj.getClass().getResourceAsStream is the
way to go. Why should you care which class loader loaded the class?
In your case, you are getting the class loader of the REPL:
getClass().getClassLoader()
res4: java.lang.ClassLoader = scala.tools.nsc.interpreter.IMain$$anon$2@64486c1a
On Sun, Feb 12, 2012 at 11:54 AM, Daniel Sobral wrote:
> Can anyone explain what's going on here? Why I can't get the resource
> from the system class loader, what object is "getClass" being called
> on, and why does it work from there?
>
> scala> val sysClassLoader = java.lang.ClassLoader.getSystemClassLoader()
> sysClassLoader: ClassLoader = sun.misc.Launcher$AppClassLoader@138d107f
>
> scala> sysClassLoader.getResourceAsStream("/org/specs2/Specification.html")
> res0: java.io.InputStream = null
>
> scala> getClass().getResourceAsStream("/org/specs2/Specification.html")
> res1: java.io.InputStream =
> sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@b37d0cf
>
> --
> Daniel C. Sobral
>
> I travel to the future all the time.