Create new Instance, get constructor by type, invoke constructor - Android java.lang.reflect

Android examples for java.lang.reflect:Constructor

Description

Create new Instance, get constructor by type, invoke constructor

Demo Code


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{
    @SuppressWarnings("unchecked")
    /**//from   w w  w.j  av  a2 s. c  o m
     * Creates a new instance of the passed class
     * @param className
     *    - the full qualified name of the class to be initialized
     * @param paramTypes
     *    - optional parameter types for the constructor
     * @param paramValues
     *    - optional parameter values for the constructor
     * @return
     *    - the new instance
     * 
     * @throws ReflectionException
     */
    public static <T> T newInstance(String className,
            Class<?>[] paramTypes, Object... paramValues)
            throws ReflectionException {

        if (paramTypes.length != paramValues.length) {
            throw new ReflectionException(
                    "parameterTypes and parameterValues must have the same length");
        }

        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new ReflectionException(e);
        } catch (ExceptionInInitializerError e) {
            throw new ReflectionException(e);
        }

        Constructor<?> ctor;
        try {
            ctor = clazz.getConstructor(paramTypes);
        } catch (SecurityException e) {
            throw new ReflectionException(e);
        } catch (NoSuchMethodException e) {
            throw new ReflectionException(e);
        }

        try {
            return (T) ctor.newInstance(paramValues);
        } catch (IllegalArgumentException e) {
            throw new ReflectionException(e);
        } catch (InstantiationException e) {
            throw new ReflectionException(e);
        } catch (IllegalAccessException e) {
            throw new ReflectionException(e);
        } catch (InvocationTargetException e) {
            throw new ReflectionException(e);
        }
    }
}

Related Tutorials