get Object Instance from class qualified name - Android java.lang.reflect

Android examples for java.lang.reflect:Class

Description

get Object Instance from class qualified name

Demo Code


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

public class Main{
    private static final String TAG = Util.getTag(ReflectionHelper.class);
    public static Object getInstance(Context context,
            String packageAndClassName) throws ReflectionHelperException {
        try {//from w ww. j  a  va 2  s  . c  o m
            return loadClass(context, packageAndClassName)
                    .getDeclaredConstructors()[0].newInstance();
        } catch (Exception e) { //TODO: Pak ind i fornuftig exception
            Log.e(TAG, "Could not create instance of class", e);
            throw new ReflectionHelperException(e);
        }
    }
    private static Class loadClass(Context context,
            String packageAndClassName) throws ReflectionHelperException {
        try {
            return context.getClassLoader().loadClass(packageAndClassName);
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Could not load class", e);
            throw new ReflectionHelperException(e);
        }
    }
}

Related Tutorials