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 ?

2
  • stackoverflow.com/a/6608848/931982 Commented May 26, 2013 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. Commented May 26, 2013 at 16:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.