[Java] Wrapper that executes private method of object from outside class

[Java] Wrapper that executes private method of object from outside class

When writing tests, I sometimes access private methods of objects, I made a simple wrapper function because I can't do it by hitting reflection directly every time.


class Main {

    /**
     *Execute private method of object
     *
     * @param target Instance of the target object
     * @param name method name
     * @param <T>Target object type
     * @throws Exception Exception at method execution
     */
    public static <T> void invokeMethod(T target, String name) throws Exception {
        final Method method = target.getClass().getDeclaredMethod(name);
        method.setAccessible(true);
        method.invoke(target);
    }

    /**
     *Execute private method of object
     *
     * @param target Instance of the target object
     * @param name method name
     * @param parameterValues List of arguments
     * @param <T>Target object type
     * @throws Exception Exception at method execution
     */
    public static <T> void invokeMethod(T target, String name, List<?> parameterValues) throws Exception {
        //Get an array of argument types
        final Class<?>[] parameterTypes = new Class[parameterValues.size()];
        parameterValues.stream().map(Object::getClass).collect(Collectors.toList()).toArray(parameterTypes);

        final Method method = target.getClass().getDeclaredMethod(name, parameterTypes);
        method.setAccessible(true);
        method.invoke(target, parameterValues.toArray());
    }

    /**
     *Execute private method of object
     *
     * @param target Instance of the target object
     * @param name method name
     * @param parameterValues List of arguments
     * @param resultType Class instance of result object
     * @param <T>Target object type
     * @param <U>Return type
     * @return value of return method
     * @throws Exception Exception at method execution
     */
    public static <T, U> U invokeMethod(T target, String name, List<?> parameterValues, Class<U> resultType) throws Exception {
        //Get an array of argument types
        final Class<?>[] parameterTypes = new Class[parameterValues.size()];
        parameterValues.stream().map(Object::getClass).collect(Collectors.toList()).toArray(parameterTypes);

        final Method method = target.getClass().getDeclaredMethod(name, parameterTypes);
        method.setAccessible(true);
        return resultType.cast(method.invoke(target, parameterValues.toArray()));
    }

    static class PrivateMethodTest {
        private void sayHelloWorld() {
            System.out.println(makeHelloMessage("world!"));
        }
        private void sayHello(String message) {
            System.out.println(makeHelloMessage(message));
        }
        private String makeHelloMessage(String message) {
            return "Hello, " + message;
        }
    }

    public static void main(String[] args) throws Exception {
        final PrivateMethodTest target = new PrivateMethodTest();

        invokeMethod(target, "sayHelloWorld");

        final List<Object> params = new ArrayList<>();
        params.add("world!");

        invokeMethod(target, "sayHello", params);

        final String message = invokeMethod(target, "makeHelloMessage", params, String.class);
        System.out.println(message);
    }
}

Recommended Posts

[Java] Wrapper that executes private method of object from outside class
[Java] Precautions when creating a process that calls a method of Abstract class using DI from a child class
[Java] Object class
Java method call from RPG (method call in own class)
Java starting from beginner, class declaration / object generation
Method name of static factory method learned from Java 8
Increment with the third argument of iterate method of Stream class added from Java9
[Java] How to use compareTo method of Date class
Java programming (class method)
Java General-purpose method that retrieves only the differences between the properties of objects of the same class
I made a Wrapper that calls KNP from Java
[Java] Object operation of ArrayList class (AOJ ④ Inversion of sequence)
[Java] Integer wrapper class reference
[Java] Comparator of Collection class
Summary of Java Math class
Benefits of Java static method
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
[Java] Private field access restrictions are not per object but per class
[Java] List method that determines whether a specific object is included
[Java] Object-oriented syntax --class method / argument
Various methods of Java String class
How to test a private method in Java and partially mock that method
From Java9, the constructor of the class corresponding to primitive types is deprecated.
I made a class that can use JUMAN and KNP from Java