Java Reflection - Java Class .getDeclaredConstructor (Class <?> . . . parameterTypes)








Syntax

Class.getDeclaredConstructor(Class <?>... parameterTypes) has the following syntax.

public Constructor <T> 
            getDeclaredConstructor(Class <?>... parameterTypes)     
            throws NoSuchMethodException,
                   SecurityException

Example

In the following code shows how to use Class.getDeclaredConstructor(Class <?>... parameterTypes) method.

//w  w  w.  j av a  2 s  .  c  o  m
import java.lang.reflect.Constructor;

public class Main {

  public static void main(String[] args) throws Exception {

    MyClass cls = new MyClass();
    Class c = cls.getClass();

    // constructor with arguments as Double and Long
    Class[] cArg = new Class[2];
    cArg[0] = Double.class;
    cArg[1] = Long.class;
    Constructor ct = c.getDeclaredConstructor(cArg);
    System.out.println("Constructor = " + ct.toString());

  }
}

class MyClass {
   MyClass() {
    System.out.println("no argument constructor");
  }

  public MyClass(Double d, Long l) {
    this.d = d;
    this.l = l;
  }

  Double d = new Double(3.4d);
  Long l = new Long(123);
}

The code above generates the following result.