Create new Instance of class by calling constructor with parameter - Android java.lang.reflect

Android examples for java.lang.reflect:Constructor

Description

Create new Instance of class by calling constructor with parameter

Demo Code


import android.content.Context;
import android.util.Log;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main{
    private static final String TAG = "";
    public static Object newInstance(String className, Object... args) {
        Object object = null;/*from w w w  .j  a  va2  s  .  co m*/
        if (Utils.hasValue(className)) {
            try {
                Class<?> adapterClass = Class.forName(className);
                Constructor<?> ct = adapterClass.getConstructor();
                object = ct.newInstance();
            } catch (ClassNotFoundException e) {
                Log.w(TAG, "ClassNotFoundException on class: " + className);
            } catch (ClassCastException e) {
                Log.w(TAG, "ClassCastException on class: " + className);
            } catch (SecurityException e) {
                Log.w(TAG, "SecurityException on class: " + className);
            } catch (NoSuchMethodException e) {
                Log.w(TAG, "NoSuchMethodException on class: " + className);
            } catch (IllegalArgumentException e) {
                Log.w(TAG, "IllegalArgumentException on class: "
                        + className);
            } catch (InstantiationException e) {
                Log.w(TAG, "InstantiationException on class: " + className);
            } catch (IllegalAccessException e) {
                Log.w(TAG, "IllegalAccessException on class: " + className);
            } catch (InvocationTargetException e) {
                Log.w(TAG, "InvocationTargetException on class: "
                        + className);
            }
        }
        return object;
    }
}

Related Tutorials