Reputation: 384
why do getClassLoader()
needs to be called using Class
object ?? why can't I simply call getClassLoader()
using the object of any class present in that package ?? for instance why cant i simply get which Classloader
loaded my class using (new Test()).getClassLoader()
?
Upvotes: 1
Views: 217
Reputation: 601
Well you need to differentiate between classes and objects.
Test t = new Test()
Will produce an object. If you want the classloader of it, you need to access the class of the object because a classloader loads classes, not objects. Let's say
ClassLoader cl = t.getClass().getClassLoader();
If you just want a reference to the classloader which loaded Test, you could also write Test.class.getClassLoader().
Upvotes: 1
Reputation: 19431
as BackSlash wrote, the ClassLoader loads the class and is referenced in the class object. If it were referenced in the instances of the class, then this reference would be attached to everey object in the VM, enlarging the size of the objects. As the objects have a reference to their class object anyway, there's no need to duplicate the classloader reference in every object.
Upvotes: 0