Android examples for java.lang.reflect:New Instance
Create singleton Instance
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.util.Log; public class Main { private static final String TAG = ""; public static Object singletonInstance(String className, String singletonMethodName) throws IllegalArgumentException { return singletonInstance(className, singletonMethodName, (Object[]) null); }//from w w w. ja v a 2 s .com public static Object singletonInstance(String className, String singletonMethodName, Object... methodArgs) throws IllegalArgumentException { try { Class<?> cls = forName(className); Method method = cls.getMethod(singletonMethodName); return method.invoke(null, methodArgs); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "IllegalAccessException when unmarshalling: " + className + " with method " + singletonMethodName); } catch (NoSuchMethodException e) { Log.e(TAG, "Method not found when unmarshalling: " + className + " with method " + singletonMethodName, e); throw new IllegalArgumentException( "NoSuchMethodException when unmarshalling: " + className + " with method " + singletonMethodName); } catch (InvocationTargetException e) { throw new IllegalArgumentException( "InvocationTargetException when unmarshalling: " + className + " with method " + singletonMethodName); } } public static Class<?> forName(String className) throws IllegalArgumentException { try { return Class.forName(className); } catch (ClassNotFoundException e) { Log.e(TAG, "Illegal access when unmarshalling: " + className, e); throw new IllegalArgumentException( "ClassNotFoundException when unmarshalling: " + className); } } }