I have a scenario in which I want to Override a constructor creation of a base class with child class based on some condition from a class.
So following are the classes: 1) Ref 2) Other (Base class) 3) OtherImpl ( Child class of Other) 4) RefWorking (Main class)
Class Ref is calling constructor of Other class, I want to override this constructor with constructor of OtherImpl.
class Ref {
private String s = "Original";
private Other o;
public Ref() {
}
public void method1(int a) {
o = new Other();
System.out.println("Method 1 : "+ s);
}
private void method2(String a) {
System.out.println("Method 2 : "+ a);
}
}
class Other {
public Other() {
System.out.println("Default Other Constructor");
}
}
class OtherImpl extends Other {
public OtherImpl() {
System.out.println("Reflection Constructor");
}
}
public class RefWorking {
public static void main(String args[]) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
Ref r = new Ref();
Class c = r.getClass();
OtherImpl oi = new OtherImpl();
Field f = c.getDeclaredField("o");
f.setAccessible(true);
f.set(r, oi);
r.method1(10);
} }
It is giving following output:
Default Other Constructor Reflection Constructor Default Other Constructor Method 1 : Original
But my expected output is : Default Other Constructor Reflection Constructor Default Other Constructor Reflection Constructor Method 1 : Original
Aucun commentaire:
Enregistrer un commentaire