2

Say, I have a class A, loaded by ClassLoader CL1.

I have another class B, loaded by ClassLoader CL2.

Assume both classes are now loaded by their respective ClassLoaders.

From A, if I execute the following statement, what would be the result : B.class.getClassLoader();

Will it return CL2? Please clarify.

Thanks HV

user127377
  • 131
  • 2
  • 10

2 Answers2

3

Will it return CL2?

In the case where it has permission to do so then yes - why wouldn't it? The result has no bearing on what class you execute the method from, it is to do with what class you execute the method on (which in this case, is B.class which was loaded by CL2.)

From the docs:

Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

If a security manager is present, and the caller's class loader is not null and the caller's class loader is not the same as or an ancestor of the class loader for the class whose class loader is requested, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the class loader for the class.

So assuming it's an actual class that you've loaded (rather than a primitive), and the security manager says that you have permission to check the class, yes - it will return the corresponding classloader (CL2 in this instance.)

Community
  • 1
  • 1
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • @user127377: The canonical way to say thanks to an answer that has helped you is to vote it up. If you believe it is the best answer, you should mark it as accepted. See http://stackoverflow.com/help/someone-answers for more information. – johnsyweb Oct 27 '13 at 09:06
1

It does return the classloader which loaded class B but caller should have permission on that class loader.

Check the API doc

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getClassLoader()

Abhijith Nagarajan
  • 3,865
  • 18
  • 23