software-mariodiana
10/29/2014 - 7:18 PM

An example of using Java's reflection to create an instance, given a class name.

An example of using Java's reflection to create an instance, given a class name.

//
// FILE: CreateSQLDateByName.java
//

// See: http://stackoverflow.com/a/6094602 & http://stackoverflow.com/a/3925617


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


public class CreateSQLDateByName {
    public static void main(String[ ] args) {
        try {
            Long timestamp = new Long(1414608968004L);
            Class<?> clazz = Class.forName("java.sql.Date");
            Constructor<?> constructor = clazz.getConstructor(Long.TYPE);
            Object object = constructor.newInstance(new Object[ ] { timestamp });
            System.out.println(object);
        }
        catch (ClassNotFoundException cnf) {
            System.err.println("Class not found: " + cnf.getMessage());
        }
        catch (NoSuchMethodException nsm) {
            System.err.println("Method not found: " + nsm.getMessage());
        }
        catch (InstantiationException ie) {
            System.err.println("Error instantiating object: " + ie.getMessage());
        }
        catch (IllegalAccessException iae) {
            System.err.println("Access error: " + iae.getMessage());
        }
        catch (InvocationTargetException ite) {
            System.err.println("Invocation target: " + ite.getMessage());
        }
    }
}