Call default private or public constructor. - Java Reflection

Java examples for Reflection:Constructor

Description

Call default private or public constructor.

Demo Code


//package com.java2s;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        System.out.println(construct(clazz));
    }/*from  w w w. j av  a  2 s  .  c  om*/

    /**
     * Call default private or public constructor.
     *
     * @param clazz class
     * @return new instance
     * @throws ReflectiveOperationException reflection exception
     */
    public static <T> T construct(final Class<T> clazz)
            throws ReflectiveOperationException {
        final Constructor<T> constructor = getDeclaredConstructor(clazz);
        final boolean isPrivate = Modifier
                .isPrivate(getModifiers(constructor));
        if (isPrivate) {
            setAccessible(constructor, true);
        }
        return getNewInstance(constructor);
    }

    private static <T> Constructor<T> getDeclaredConstructor(
            final Class<T> clazz) throws NoSuchMethodException,
            SecurityException {
        return clazz.getDeclaredConstructor();
    }

    private static <T> int getModifiers(final Constructor<T> constructor) {
        return constructor.getModifiers();

    }

    private static void setAccessible(final Constructor<?> constructor,
            final boolean value) {
        constructor.setAccessible(value);
    }

    private static <T> T getNewInstance(final Constructor<T> constructor)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        return constructor.newInstance();
    }
}

Related Tutorials