Create a new instance of a class by calling a constructor with arguments : Constructor « Class « Java






Create a new instance of a class by calling a constructor with arguments

   

import java.lang.reflect.Constructor;

/**
 * Handy reflection routines.
 */
public abstract class Reflect {
  /**
   * Create a new instance of a class by calling a constructor with arguments.
   */
  public static Object newInstance(String className, Class[] signature, Object[] args)
      throws Exception {

    Class cls = Class.forName(className);
    Constructor constructor = cls.getConstructor(signature);
    return constructor.newInstance(args);
  }

}

   
    
    
  








Related examples in the same category

1.Paying attention to exceptions in constructorsPaying attention to exceptions in constructors
2.Order of constructor callsOrder of constructor calls
3.Constructors and polymorphism don't produce what you might expectConstructors and polymorphism don't produce what you might expect
4.Constructor initialization with compositionConstructor initialization with composition
5.Demonstration of a simple constructorDemonstration of a simple constructor
6.Constructors can have argumentsConstructors can have arguments
7.Show Constructors conflicting
8.Show that if your class has no constructors, your superclass constructors still get calledShow that if your class has no constructors, your superclass constructors still get called
9.Constructor calls during inheritanceConstructor calls during inheritance
10.A constructor for copying an object of the sameA constructor for copying an object of the same