1

I am trying to read the resource by the class loader.

but meanwhile, I found that , the class object also could finish such a thing.

my code is like this.

  1. Teacher.class.getResource("1.txt");

  2. Teacher.class.getClassLoader.getResource("1.txt");

the two ways could get the resource I wanted, however, I don't understand the underlying theory.

Is there anybody who can help me ?

  • http://stackoverflow.com/a/6608848/931982 – stinepike May 26 '13 at 16:51
  • after I tracked the source code, found code snippet like this. name = resolveName(name); ClassLoader cl = getClassLoader0(); if (cl==null) { // A system class. return ClassLoader.getSystemResource(name); } return cl.getResource(name); so the answer is method 1 will call method 2. Thanks all the same. – user1885152 May 26 '13 at 16:57

1 Answers1

3

Just checked the specification and it says this:

Class.getResource(String resource)

ClassLoader.getResource(String resource)

Class's getResource() - documentation states the difference:

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136