• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Constructor.newInstance() method Example

October 2, 2015 by javainterviewpoint 1 Comment

In my previous article we have seen how to use Class.newInstance() method in creating object for class dynamically but there exist a problem the newInstance() method of Class class can invoke only no-arg constructor of the class when a class has parameterized constructors we cannot use newInstance() method of Class class at that place we need to go for the newInstance() method of the Constructor class. Here also we will load the class using Class.forName() method and get the class instance and get the constructor in the class. Lets see how we can achieve it.

Example of Constructor.newInstance() method

Lets now take a look into the below example for a better understanding.

Employee.java

Our Employee class is a simple Java concrete class with three attributes namely empId, empName, empSalary and their corresponding getters and setters.

public class Employee
{

    private int empId;
    private String empName;
    private int empSalary;
    public Employee(int empId, String empName, int empSalary) {
        this.empId = empId;
        this.empName = empName;
        this.empSalary = empSalary;
    }
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public int getEmpSalary() {
        return empSalary;
    }
    public void setEmpSalary(int empSalary) {
        this.empSalary = empSalary;
    }
}

ConstructorNewInstanceExample.java

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

public class ConstructorNewInstanceExample 
{
    public static void main(String args[])
    {
        try 
        {
            Class clasz = Class.forName("com.javainterviewpoint.Employee");
            Constructor constructor = clasz.getConstructor(new Class[]{int.class,String.class,int.class});
            Employee employee = (Employee)constructor.newInstance(1,"JavaInterviewPoint",45000);
            System.out.println("Employee Id     : "+employee.getEmpId());
            System.out.println("Employee Name   : "+employee.getEmpName());
            System.out.println("Employee Salary : "+employee.getEmpSalary());
            
        }
        catch (NoSuchMethodException e) 
        {
            e.printStackTrace();
        }
        catch (SecurityException e) 
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (InstantiationException e) 
        {
            e.printStackTrace();
        } catch (IllegalAccessException e) 
        {
            e.printStackTrace();
        } catch (IllegalArgumentException e) 
        {
            e.printStackTrace();
        } catch (InvocationTargetException e) 
        {
            e.printStackTrace();
        }
    }
}

The below line creates the object of type Class which encapsulates the Employee class.

Class clasz = Class.forName("com.javainterviewpoint.Employee);

We can get a particular constructor by calling getConstructor() method of clasz. Parameter passed should be of Class type matching the actual parameter of the Employee class. In Employee class we have one parameterized constructor taking int,string,int parameters

public Employee(int empId, String empName, int empSalary) {
        this.empId = empId;
        this.empName = empName;
        this.empSalary = empSalary;
    }

and hence we have passed int.class,String.class,int.class to the get that particular constructor.

Constructor constructor = clasz.getConstructor(new Class[]{int.class,String.class,int.class});

Finally newInstance() method of the Constructor class is called with parameters matching the constructor passed to get our Employee object.

Employee employee = (Employee)constructor.newInstance(1,"JavaInterviewPoint",45000);

When we run the above code we will get the below output.

Output:

Employee Id     : 1
Employee Name   : JavaInterviewPoint
Employee Salary : 45000

What if more than one parameterized constructors are there?

When we have more than one constructor, lets see how we can pass-in the parameters dynamically and create objects. Lets make our Employee class to have more than one parameterized constructor.

Employee.java
Lets modify our Employee class to have 2 parameterized constructors. One constructor having three parameters (empId,empName,empSalary) and other having two parameters (empId,empName)

public class Employee
{
    private static int empId;
    private String empName;
    private int empSalary;
    
    public Employee(int empId, String empName, int empSalary) {
        this.empId = empId;
        this.empName = empName;
        this.empSalary = empSalary;
    }
    public Employee(int empId, String empName) {
        this.empId = empId;
        this.empName = empName;
    }
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public int getEmpSalary() {
        return empSalary;
    }
    public void setEmpSalary(int empSalary) {
        this.empSalary = empSalary;
    }
}

ConstructorNewInstanceExample.java

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

public class ConstructorNewInstanceExample 
{
    public static void main(String args[])
    {
        try 
        {
            Class clasz = Class.forName("com.javainterviewpoint.Employee");
            Constructor[] allConstructors = clasz.getConstructors();
            
            Class[] parametersOfConstructor1 = allConstructors[0].getParameterTypes();
            Constructor constructor1 = clasz.getConstructor(parametersOfConstructor1);
            Employee employee1 = (Employee)constructor1.newInstance(1,"JavaInterviewPoint11");
            System.out.println("***Employee1 Values***");
            System.out.println("Employee Id     : "+employee1.getEmpId());
            System.out.println("Employee Name   : "+employee1.getEmpName());
            employee1.setEmpSalary(1111);//Setting salary since not set through constructor
            System.out.println("Employee Salary : "+employee1.getEmpSalary());
            
            Class[] parametersOfConstructor2 = allConstructors[1].getParameterTypes();
            Constructor constructor2 = clasz.getConstructor(parametersOfConstructor2);
            Employee employee2 = (Employee)constructor2.newInstance(2,"JavaInterviewPoint22",22222);
            System.out.println("***Employee2 Values***");
            System.out.println("Employee Id     : "+employee2.getEmpId());
            System.out.println("Employee Name   : "+employee2.getEmpName());
            System.out.println("Employee Salary : "+employee2.getEmpSalary());
            
        }
        catch (NoSuchMethodException e) 
        {
            e.printStackTrace();
        }
        catch (SecurityException e) 
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (InstantiationException e) 
        {
            e.printStackTrace();
        } catch (IllegalAccessException e) 
        {
            e.printStackTrace();
        } catch (IllegalArgumentException e) 
        {
            e.printStackTrace();
        } catch (InvocationTargetException e) 
        {
            e.printStackTrace();
        }
    }
}

The below line creates Object of Class type

Class clasz = Class.forName("com.javainterviewpoint.Employee");

Now we get all the Constructors available in the Employee class using getConstructors() method, which returns array Constructor[]

Constructor[] allConstructors = clasz.getConstructors();

We can get the list of all parameter available for a particular constructor through constructor.getParameterTypes() method. It will be returning an array Class[]

Class[] parametersOfConstructor1 = allConstructors[0].getParameterTypes();

Get the particular Constructor by passing Parameter obtained in the previous step

Constructor constructor1 = clasz.getConstructor(parametersOfConstructor1);

Finally create object for our Employee class by calling constructor.newInstance() and passing the corresponding parameters.

Employee employee1 = (Employee)constructor1.newInstance(1,"JavaInterviewPoint11");

Output :

***Employee1 Values***
Employee Id     : 1
Employee Name   : JavaInterviewPoint11
Employee Salary : 1111
***Employee2 Values***
Employee Id     : 2
Employee Name   : JavaInterviewPoint22
Employee Salary : 22222

Other interesting articles which you may like …

  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Constructor in Java and Types of Constructors in Java
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: constructor, Constructor.newInstance(), getConstructor(), Java, Java Constructor.newInstance(), newInstance(), parameterized constructors

Comments

  1. Amol A. Ghadigaonkar says

    March 5, 2017 at 10:26 am

    Feeling absolutely grateful to learn this code from here…This made a lot of things easy for me…Thanks. 🙂

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·