instantiates and returns a Object - Android java.lang.reflect

Android examples for java.lang.reflect:New Instance

Description

instantiates and returns a Object

Demo Code


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import android.util.Log;

public class Main{
    private static boolean debug = true;
    /**//from  w ww. ja va2 s . c o  m
     * createObject() - instantiates and returns a Object
     * 
     * @param c
     *            Class type of the object
     * @param paramTypes
     *            Types of the parameters (null if none)
     * @param params
     *            Parameters (null if none)
     */
    public static Object createObject(Class<?> c, Class<?>[] paramTypes,
            Object[] params) throws IllegalArgumentException {
        Object o = null;

        try {
            Constructor<?> cst = c.getConstructor(paramTypes);
            o = cst.newInstance(params);
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
        }

        return o;
    }
    /**
     * createObject() - instantiates and returns a Object
     * 
     * @param packageName
     *            name of the containing package
     * @param className
     *            name of the class
     * @param paramTypes
     *            Types of the parameters (null if none)
     * @param params
     *            Parameters (null if none)
     */
    public static Object createObject(String packageName, String className,
            Class<?>[] paramTypes, Object[] params)
            throws IllegalArgumentException {
        Object o = null;

        try {
            Class<?> c = getClass(packageName, className);
            Constructor<?> cst = c.getConstructor(paramTypes);
            o = cst.newInstance(params);
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
        }

        return o;
    }
    /**
     * getClass() - returns a Class<?> from its name
     * 
     * @param packageName
     *            name of the containing package
     * @param className
     *            name of the class
     */
    public static Class<?> getClass(String packageName, String className) {
        Class<?> c = null;

        try {
            StringBuilder sb = new StringBuilder(packageName);
            sb.append(".");
            sb.append(className);

            c = Class.forName(sb.toString());
        } catch (ClassNotFoundException e) {
        }
        return c;
    }
}

Related Tutorials