Call private constructor using reflection This is useful in code coverage tests - Android java.lang.reflect

Android examples for java.lang.reflect:Constructor

Description

Call private constructor using reflection This is useful in code coverage tests

Demo Code

/*//from  ww  w  . java 2s  .  c  o  m
 * ClassUtil.java
 * 
 * Avaya Inc. - Proprietary (Restricted) Solely for authorized persons having a
 * need to know pursuant to Company instructions.
 * 
 * Copyright 2013 Avaya Inc. All rights reserved. THIS IS UNPUBLISHED
 * PROPRIETARY SOURCE CODE OF Avaya Inc. The copyright notice above does not
 * evidence any actual or intended publication of such source code.
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;

public class Main{
    private static final String TAG = ClassUtil
            .getShortName(ClassUtil.class);
    /**
     * Call private constructor using reflection
     * <p>
     * This is useful in code coverage tests
     * 
     * @param clazz - Class to instantiate
     */
    public static boolean callPrivateConstructor(Class<?> clazz) {
        try {
            Constructor<?> c = clazz.getDeclaredConstructor();

            if (Modifier.isPrivate(c.getModifiers())) {
                c.setAccessible(true);
                c.newInstance();
            } else {
                Log.e(TAG, "Constructor is not private");
                return false;
            }
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage(), ex);
            return false;
        }

        return true;
    }
}

Related Tutorials