How do I create object using Constructor object?

The example below using a constructor reflection to create a string object by calling String(String) and String(StringBuilder) constructors.

package org.kodejava.lang.reflect;

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

public class CreateObjectDemo {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        try {
            Constructor<String> constructor = clazz.getConstructor(String.class);

            String object = constructor.newInstance("Hello World!");
            System.out.println("String = " + object);

            constructor = clazz.getConstructor(StringBuilder.class);
            object = constructor.newInstance(new StringBuilder("Hello Universe!"));
            System.out.println("String = " + object);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
Wayan

Leave a Reply

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