Junior
Aké sú dôvody na používanie Wrapper tried?
sobes.tech AI
Odpoveď od AI
- Testovanie súkromných metód
- Integrácia s legacy kódom
- "Uľahčenie" zložitých rozhraní
- Poskytovanie dodatočnej funkčnosti (záznam, metriky, spracovanie chýb)
- Prispôsobenie externých knižníc požiadavkám projektu
- Simulácia správania externých služieb (mocks, stuby)
Napríklad, wrapper na testovanie súkromnej metódy v Jave:
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;
}
}
Použitie obalu:
// Trieda s privátnou metódou
class MyClass {
private int privateMethod(int a, int b) {
return a + b;
}
}
// Testovanie privátnej metódy pomocou obalu
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("Výsledok: " + result); // Výstup: Výsledok: 5
}
}