user127377
user127377

Reputation: 151

java : ClassLoaders

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

Upvotes: 2

Views: 98

Answers (2)

Michael Berry
Michael Berry

Reputation: 72254

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.)

Upvotes: 3

Abhijith Nagarajan
Abhijith Nagarajan

Reputation: 4030

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()

Upvotes: 1

Related Questions