Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.programmer Subject: Re: ClassLoader.getSystemResourceAsStream versus this.getClass().getResourceAsStream() Date: Mon, 03 Dec 2012 12:07:45 -0800 Organization: A noiseless patient Spider Lines: 39 Message-ID: References: <3c227741-7b7f-4cf8-b188-ce5268894031@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Mon, 3 Dec 2012 20:07:47 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="61282af8d6595e8d991edb5ac03d6e00"; logging-data="16304"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Wj5T7RoGV+rkB7yFKuz5e2X3p1lh0PgI=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Thunderbird/17.0 In-Reply-To: <3c227741-7b7f-4cf8-b188-ce5268894031@googlegroups.com> Cancel-Lock: sha1:MaW0GT/8gjiVjYHvZecgwuSgyhk= Xref: csiph.com comp.lang.java.programmer:20079 On 12/3/2012 11:29 AM, zyng wrote: > I am sure the difference between the two have been discussed well: > the first one is using the System classloader and the second one is > using the class loader which has loaded this class, most likely a > child of System classloader, according to what I have found on the > web. First, note that there are two separate objects here, ClassLoader and Class. Just because the names of their respective methods are the named the same, doesn't mean they do the same thing. > > //option 1: InputStream is = > ClassLoader.getSystemResourceAsStream("hij/hello.txt"); > > //option 2: InputStream is = > ResourceTools.class.getResourceAsStream("/hij/hello.txt"); Note in the documentation of the second method call: " This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String)." So it's different because it delegates to a different method. I have to guess that the two methods are designed to do different things, in spite of their identical names. I suppose this could be considered a "gotcha." My advice is to consider option 2; I've never seen the first form in actual practice. Why they did things this way, I have no idea. Classloading pretty confusing except in trivial cases. I think it's best to keep things as simple as possible when you resort to loading manually. For extra fun, look at Thread::getContextClassLoader, which is even more correct than option 1 or 2 above in certain circumstances (mainly web apps).