Sunday, November 8, 2009

Can we have two java.lang.Class instances of the same Type?

Can we have two java.lang.Class instances of the same Type?

Yeah... we can have any number of java.lang.Class instances of the same type provided we get the Type loaded by a different ClassLoader instance everytime. Please note that even if we use the same ClassLoader class, but if we use different instances of that class to load a Java Type then each time we'll get a different java.lang.Class instance for the loaded Type. If no ClassLoader instance is explicitly specified then the default ClassLoader instance used which the user doesn't need to create instead JVM creates and maintains for the users.

The loadClass method of the ClassLoader class is used to load any Java Type. This method has two variants:
  • public Class loadClass(String name) - this variant accepts only a String type parameter asking the caller to supply the name of the class
  • protected Class loadClass(String name, boolean resolve) - this variant accepts one additional boolean type parameter asking the caller to specify if the loaded class should be linked immediately or not. Default value of this parameter is false and hence a loadClass(className1) call is internally converted into loadClass(className1, false) call
As you would have noticed that both these methods are instance methods and hence they can be called only on an instance of type ClassLoader. You can create your own instances of any valid ClassLoader type and call the loadClass method to load a Java class to have separate java.lang.Class instances every time you use a separate instance of type ClassLoader to call the loadClass method upon.

No comments:

Post a Comment