Sobes.tech
Junior

What are the reasons for using wrapper classes?

sobes.tech AI

Answer from AI

  • Testing private methods
  • Integration with legacy code
  • "Simplification" of complex interfaces
  • Providing additional functionality (logging, metrics, error handling)
  • Adapting third-party libraries to project requirements
  • Mocking external services (stubs, mocks)

For example, a wrapper for testing a private method in Java:

import java.lang.reflect.Method;

public class PrivateMethodWrapper {

    private Object instance;
    private Class<?> clazz;

    public PrivateMethodWrapper(Object instance) {
        this.instance = instance;
        this.clazz = instance.getClass();
    }

    public Object invokePrivateMethod(String methodName, Object... args) throws Exception {
        Method method = clazz.getDeclaredMethod(methodName, getParameterTypes(args));
        method.setAccessible(true);
        return method.invoke(instance, args);
    }

    private Class<?>[] getParameterTypes(Object... args) {
        Class<?>[] types = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            types[i] = args[i].getClass();
        }
        return types;
    }
}

Using the wrapper:

// Class with a private method
class MyClass {
    private int privateMethod(int a, int b) {
        return a + b;
    }
}

// Testing the private method using the wrapper
public class MyClassTest {
    public void testPrivateMethod() throws Exception {
        MyClass instance = new MyClass();
        PrivateMethodWrapper wrapper = new PrivateMethodWrapper(instance);
        Object result = wrapper.invokePrivateMethod("privateMethod", 2, 3);
        System.out.println("Result: " + result); // Output: Result: 5
    }
}