[英]Override super class constructor with base class constructor using Reflection
我有一種情況,在這種情況下,我想根據某個類的某些條件,使用子類覆蓋基類的構造函數創建。
因此,以下是這些類:1)Ref 2)Other(基礎類)3)OtherImpl(Other的子類)4)RefWorking(主類)
類Ref正在調用Other類的構造函數,我想用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);
}
}
它給出以下輸出:
默認其他構造函數反射構造函數默認其他構造函數方法1:原始
但我的預期輸出是:默認其他構造函數反射構造函數默認其他構造函數反射構造函數方法1:原始
恐怕您不能重寫base class constructor
,因為OtherImpl class
不能繼承Other Class
的構造函數 ,更不用說重寫它了。
這篇文章可能會對您有所幫助。 構造函數可以覆蓋嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.