Call a private method of a given class object - with no parameters - Android java.lang.reflect

Android examples for java.lang.reflect:Object Type

Description

Call a private method of a given class object - with no parameters

Demo Code

/*/*from   w w w.ja v a 2  s.com*/
 * 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.
 */
//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /**
     * Call a private method of a given class object - with no parameters
     * 
     * @param objectInstance Class object to invoke method on
     * @param methodName Method name to invoke
     * @param inputVal
     * @return Return value from invoked method
     * 
     * @throws IllegalArgumentException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Object callPrivateMethod(Object objectInstance,
            String methodName) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException // NOSONAR
    {
        Object[] params = null;

        Method method = objectInstance.getClass().getDeclaredMethod(
                methodName, (Class[]) null);

        method.setAccessible(true);

        return method.invoke(objectInstance, params);
    }

    /**
     * Call a private method of a given class object
     * 
     * @param objectInstance Class object to invoke method on
     * @param methodName Method name to invoke
     * @param int1 int Parameter to the method
     * @return Return value from invoked method
     * 
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Object callPrivateMethod(Object objectInstance,
            String methodName, int int1) throws NoSuchMethodException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException // NOSONAR
    {

        Method method = objectInstance.getClass().getDeclaredMethod(
                methodName, Integer.TYPE);

        method.setAccessible(true);

        return method.invoke(objectInstance, int1);
    }
}

Related Tutorials