Java Reflection and Constructors

How to create objects of a class with the Java Reflection.

Create an object with a constructor which have arguments.

  • To instantiate an object with a constructor with argument, you need to use the Constructor object.

The newInstance() method

  • The Constructor class provides a newInstance() method which takes an array of Objects for the parameter values.
    1. You must first set up an array of Class objects with the correct types for the constructor you want:
      Class[] parmTypes = {String.class, int.class, int.class, Color.class};
    2. The next thing is to get a reference to the constructor using the getConstructor() method that takes a parameter with an array of class objects:
      Class rectangleClassObject = Rectangle.class;
      Constructor constructor = rectangleClassObject.getConstructor(parmTypes);
    3. Then, fill up an array with object values you want to use in creating an object of your class (Rectangle):
       Object[] parms = {"Rom A", 7, 10, Color.red};
    4. At last create the Object with the newInstance() using the array of Object values as parameter:
      Rectangle p = (Rectangle) constructor.newInstance(parms);

An example where we use the method mention above.

  • You must catch any exceptions that may occur in this sequence of statements. Here is an application example that shows this:
    First, we need a class to our analysis:
    package createobject;
    
    import java.awt.Color;
    
    public class Rectangle   {
      private String name;
      private int length;
      private int width;
      private Color color;
      public Rectangle() {
        this("undefined", 10, 10, Color.white);
      }
      @Override
      public String toString() {
        return " Name: " +
        name+" width: " + width + " length: " + length + " color: " + color;
      }
      public Rectangle(String name, int width, int length, Color color) {
        this.name=name;
        this.length = length;
        this.width = width;
        this.color = color;
      }
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public int getLength() {
        return length;
      }
      public void setLength(int length) {
        this.length = length;
      }
      public int getWidth() {
        return width;
      }
      public void setWidth(int width) {
        this.width = width;
      }
      public Color getColor() {
        return color;
      }
      public void setColor(Color color) {
        this.color = color;
      }
    }
    Here are the main class that creates an object of the Rectangle class using the Constructor class:
    package createobject;
    
    import java.awt.Color;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Main {
      public static void main(String[] args) {
        // An array of Class objects with the correct types for the constructor
        Class[] parmTypes = {String.class, int.class, int.class, Color.class};
        // Get a reference to the constructor we want to use
        Class rectangleClassObject = Rectangle.class;
        Constructor constructor = null;
        try {
          constructor = rectangleClassObject.getConstructor(parmTypes);
        } catch (NoSuchMethodException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        // An array with object values we want to use
         Object[] parms = {"Room A", 7, 10, Color.red};
        // create the Object with the newInstance() method
        try {
          Rectangle p = (Rectangle) constructor.newInstance(parms);
          System.out.println(p);
        } catch (InstantiationException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    Please note which exceptions you must catch.
    The result of this is:
    Name: Room A width: 7 length: 10 color: java.awt.Color[r=255,g=0,b=0]
    You can download this example here (needed tools can be found in the right menu on this page).

Finding more about the Constructors.

  • For each Constructor that exist in the class you can find the parameter types.
    Here is an example using the Rectangle class above:
    package listconstructors;
    
    import java.lang.reflect.Constructor;
    
    public class Main {
    
      public static void main(String[] args) {
        System.out.println("\nFind declared constructors and its parameter types:");
        Class rectangleClassObject = Rectangle.class;
        Constructor[] constructors = rectangleClassObject.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
          System.out.print(constructor.getName() + "(");
          // Find all the parameter types for the constructor
          Class[] paratypes = constructor.getParameterTypes();
          String comma = "";
          for (Class paratype : paratypes) {
            System.out.print(comma + paratype.getName());
            comma = ",";
          }
          System.out.println(")");
        }
      }
    }
    The result of this is:
    Find declared constructors and its parameter types:
    listconstructors.Rectangle(java.lang.String,int,int,java.awt.Color)
    listconstructors.Rectangle()
    You can download this example here (needed tools can be found in the right menu on this page).
Prev. in menu JavaReflection/Constructors.php Next in menu
Prev. in menu JavaReflection/Constructors.php Next in menu
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.