Java Object Creation By Constructor New Instance Method

java.lang.reflect.Constructor class provides the newInstance() method for object creation. The Constructor class newInstance() method is similar to the java.lang.Class class newInstance() method.

package org.wesome.dsalgo.design.pattern;

import java.lang.reflect.Constructor;

public class Apple {
    String name = "McIntosh";

    public Apple() {
        System.out.println("Apple default constructor");
    }

    public static void main(String[] args) {
        try {
            Constructor<Apple> constructor = Apple.class.getDeclaredConstructor();
            Apple apple = constructor.newInstance();
            System.out.println("apple = " + apple.name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

follow us on