invoke Constructor - Android java.lang.reflect

Android examples for java.lang.reflect:Constructor

Description

invoke Constructor

Demo Code


//package com.java2s;

import java.lang.reflect.Constructor;

public class Main {
    public static <T> T invokeConstructor(Class<T> clazz) {
        return invokeConstructor(clazz, new Class[] {}, new Object[] {});
    }//from   www .  j a v  a 2s.c  o  m

    public static <T> T invokeConstructor(Class<T> clazz,
            Class<?>[] parameterTypes, Object[] values) {
        if (clazz == null)
            return null;
        if (parameterTypes == null)
            return null;
        if (values == null)
            return null;

        try {
            Constructor<T> ctor = clazz
                    .getDeclaredConstructor(parameterTypes);
            if (ctor != null) {
                ctor.setAccessible(true);
                return ctor.newInstance(values);
            }
        } catch (Throwable ex) {
            return null;
        }

        return null;
    }

    public static <T> T newInstance(Class<T> clazz) {
        try {
            Constructor<T> ctor = clazz.getDeclaredConstructor();
            ctor.setAccessible(true);
            return ctor.newInstance();
        } catch (Throwable ex) {
            throw new IllegalStateException(ex);
        }
    }

    public static <T> T newInstance(Class<T> clazz,
            Class<?>[] parameterTypes, Object[] args) {
        try {
            Constructor<T> ctor = clazz
                    .getDeclaredConstructor(parameterTypes);
            ctor.setAccessible(true);
            return ctor.newInstance(args);
        } catch (Throwable ex) {
            throw new IllegalStateException(ex);
        }
    }
}

Related Tutorials