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();
        }
    }
}

How do I invoke a method using Method class?

This example demonstrate using reflection to invoke methods of a class object. Using reflection we can call method of an object using the given string name of the method. When using this method we need to catch for the NoSuchMethodException, IllegalAccessException and InvocationTargetException.

package org.kodejava.lang.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class InvokingMethod {
    public static void main(String[] args) {
        InvokingMethod object = new InvokingMethod();
        Class<? extends InvokingMethod> clazz = object.getClass();

        try {
            // Invoking the add(int, int) method
            Method method = clazz.getMethod("add", int.class, int.class);
            Object result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

            // Invoking the multiply(int, int) method
            method = clazz.getMethod("multiply", int.class, int.class);
            result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public int add(int numberA, int numberB) {
        return numberA + numberB;
    }

    public int multiply(int numberA, int numberB) {
        return numberA * numberB;
    }
}