Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting Classloader as null when loading class using Class.forName()

 
Abhineet Kapil
Ranch Hand
Posts: 52
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am loading class Test2 from class Test using Class.forName().
But when I try to get the classLoader for class Test2, i get null value.
Both classes are in the same folder.


Class Test2 :


Class Test :




Can anyone please explain why I am getting classloader as null.
Should'nt it return the same classloader as that of class Test.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API documentation of Class.getClassLoader() says:
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.

Abhineet Kapil wrote:Should'nt it return the same classloader as that of class Test.

Did you try checking what the classloader is that was used to load class Test? Maybe it's also null. Try: Test.class.getClassLoader()
 
Abhineet Kapil
Ranch Hand
Posts: 52
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I checked the classloader of Test class. It is not null.

Below is the output :

ClassLoader of Test class : sun.misc.Launcher$AppClassLoader@14fe5c
ClassLoader of Test2 class : null
 
Abhineet Kapil
Ranch Hand
Posts: 52
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have observed different behaviour when I call getClassLoader() through object reference and through Class object.



Output of above code :



So, why is there a difference when getting class loader from a object reference and that from Class name.
 
Tony Docherty
Bartender
Posts: 2952
59
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference you are seeing is when you are calling getClass().getClassLoader() on a Class object. This is asking for the class loader that loaded the Class object (which is presumably the bootstrap class loader) and not the class loader that loaded the test2 class.
IF you change your code to:
You will get the answer you expected.
 
Abhineet Kapil
Ranch Hand
Posts: 52
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Tony...

Working perfectly fine now...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic