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.example.reflect;

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

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

        try {
            Constructor constructor = clazz.getConstructor(new Class[] {String.class});

            String object = (String) constructor.newInstance(new Object[] {"Hello World!"});
            System.out.println("String = " + object);

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

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

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