Sunday 27 May 2018

Constructor: Define an object using constructor arguments

‘java.lang.reflect.Constructor’ class provides ‘newInstance’ method to create an instance of an object.

public T newInstance(Object ... initargs)
Based on the arguments, it instantiates an object.

For example,

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public Employee() {

 }

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}


Below step-by-step procedure explains how to create an object to the class Employee using parameterized constructor.

Step 1: Get all the constructors of the class Employee.
Constructor<Employee>[] constructors = (Constructor<Employee>[]) Employee.class.getConstructors();

Step 2: Check the number of parameters on each constructor, if number of parameters are 2, then create an employee object by calling newInstance method.

Employee emp = null;
for (Constructor<Employee> constructor : constructors) {
 int parametersLength = constructor.getParameterTypes().length;
   
 if (parametersLength != 2)
  continue;

 emp = constructor.newInstance(1, "Hari Krishna");
}

Test.java

package com.sample.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  Constructor<Employee>[] constructors = (Constructor<Employee>[]) Employee.class.getConstructors();

  Employee emp = null;
  for (Constructor<Employee> constructor : constructors) {
   int parametersLength = constructor.getParameterTypes().length;
   if (parametersLength != 2)
    continue;

   emp = constructor.newInstance(1, "Hari Krishna");
  }
  
  System.out.println(emp);
 }
}


Output
Employee [id=1, name=Hari Krishna]

In this case, the example is very simple, in real world, you may have to check number of arguments, type and order of the arguments also.


Previous                                                 Next                                                 Home

No comments:

Post a Comment