Java Method Call invokePrivateMethod(Object instance, String name, Object... args)

Here you can find the source of invokePrivateMethod(Object instance, String name, Object... args)

Description

invoke Private Method

License

Open Source License

Declaration

public static final <T> T invokePrivateMethod(Object instance, String name, Object... args) 

Method Source Code


//package com.java2s;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static final <T> T invokePrivateMethod(Object instance, String name, Object... args) {

        Class<?>[] clazArray = new Class<?>[args.length];

        for (int i = 0; i < args.length; i++) {
            clazArray[i] = args[i].getClass();
        }//  w w w  . ja v a 2 s.  c  o  m

        try {
            Method method = instance.getClass().getDeclaredMethod(name, clazArray);
            method.setAccessible(true);

            T result = (T) method.invoke(instance, args);
            return result;

        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException e) {

            throw new RuntimeException(e);
        }
    }

    public static final <T> T invokePrivateMethod(Object instance, String name) {

        try {
            Method method = instance.getClass().getDeclaredMethod(name);
            method.setAccessible(true);

            T result = (T) method.invoke(instance);
            return result;

        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException e) {

            throw new RuntimeException(e);
        }
    }
}

Related

  1. invokePrepare(Object instance)
  2. invokePrimivite(Object entity, Method writeMethod, Class propertyType, String propertyValue)
  3. invokePrivate(Class clazz, Object instance, String methodName, Class[] argTypes, Object[] args)
  4. invokePrivate(String name, final Object obj, Object[] objects)
  5. invokePrivateMethod(Method method, Object object, Object... args)
  6. invokePrivateMethod(Object obj, String methodName, Class[] parameterTypes, Object[] args)
  7. invokePrivateMethod(String methodName, Class clazz, Object object)
  8. invokeProperty(Object obj, String property)
  9. invokeProtectedMethod(Class c, String method, Object... args)