Thursday, 18 June 2015

How to load class dynamically?

Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time.

Class.forName (String className);  //forname -static method which returns a Class

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an
instance of the loaded class. It’s just like creating a class object with no arguments.
class.newInstance ();      
  //A non-static method, which creates an instance of a  class (i.e. creates  an object).
Ex:
// variable fully qualified class name, as a String!!
String className = "com.mindprod.holidays.Christmas";
// Create a class Christmas object, with an interface HolInfo reference
HolInfo holidayDelegate = (HolInfo)( Class.forName( className ).newInstance() );
// Execute methods of the Christmas object.
String celebrated = holidayDelegate.getHowCelebrated();
For reference ,Methods definitions in Class :
 public static Class<?> forName(String className)
                        throws ClassNotFoundException
className - the fully qualified name of the desired class.
public T newInstance()
              throws InstantiationException,
                     IllegalAccessException

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.

No comments:

Post a Comment