call Private Method - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

call Private Method

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static Object callPrivateMethod(Object obj, String methodName,
            Object... params) {/*from   w  w w  .  j  a va  2s . c  o m*/
        try {
            Class[] paramsClass = null;
            if (params != null && params.length > 0) {
                paramsClass = new Class[params.length];
                for (int i = 0; i < paramsClass.length; i++) {
                    paramsClass[i] = params[0].getClass();
                }
            }
            Method method = obj.getClass().getDeclaredMethod(methodName,
                    paramsClass);
            if (method == null) {
                return null;
            }
            method.setAccessible(true);
            return method.invoke(obj, params);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static Object callPrivateMethod(Class whichClass, Object obj,
            String methodName, Object... params) {
        try {
            Class[] paramsClass = null;
            if (params != null && params.length > 0) {
                paramsClass = new Class[params.length];
                for (int i = 0; i < paramsClass.length; i++) {
                    paramsClass[i] = params[0].getClass();
                }
            }
            Method method = whichClass.getDeclaredMethod(methodName,
                    paramsClass);
            if (method == null) {
                return null;
            }
            method.setAccessible(true);
            return method.invoke(obj, params);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static Object callPrivateMethod(Class whichClass, Object obj,
            String methodName, Class[] paramsClass, Object... params) {
        try {
            Method method = whichClass.getDeclaredMethod(methodName,
                    paramsClass);
            if (method == null) {
                return null;
            }
            method.setAccessible(true);
            return method.invoke(obj, params);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Related Tutorials