Java - Create object via Class by invoking a constructor

Introduction

You must get the reference to the constructor first.

Person class has a constructor with a signature Person(int id, String name).

You can get the reference of this constructor as shown:

Constructor<Person> cons = personClass.getConstructor(int.class, String.class);

Demo

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

public class Main {
  public static void main(String[] args) {
    Class<Person> personClass = Person.class;
    try {//from  w  w  w . j a  v  a 2s  . co  m
      // Get the constructor "Person(int, String)"
      Constructor<Person> cons = personClass.getConstructor(int.class, String.class);

      // Invoke the constructor with values for id and name
      Person chris = cons.newInstance(2018, "book2s.com");
      System.out.println(chris);
    } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException e) {
      System.out.println(e.getMessage());
    }
  }
}

class Person {
  private int id = -1;
  private String name = "Unknown";

  public Person() {
  }

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

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

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

  public String toString() {
    return "Person: id=" + this.id + ", name=" + this.name;
  }
}

Result

Related Topic