Junior
Quali sono le ragioni per usare le classi Wrapper?
sobes.tech AI
Risposta dell'AI
- Test delle metodi privati
- Integrazione con codice legacy
- "Alleggerimento" di interfacce complesse
- Fornitura di funzionalità aggiuntive (registrazione, metriche, gestione degli errori)
- Adattamento di librerie di terze parti ai requisiti del progetto
- Simulazione del comportamento di servizi esterni (mock, stub)
Ad esempio, un wrapper per testare un metodo privato 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;
}
}
Utilizzo del wrapper:
// Classe con metodo privato
class MyClass {
private int privateMethod(int a, int b) {
return a + b;
}
}
// Test del metodo privato con il 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("Risultato: " + result); // Output: Risultato: 5
}
}