[英]Java Constructor with extends keyword
我有一個看起來像這樣的java類:
public class thisThing {
private final Class<? extends anInterface> member;
public thisThing(Class<? extends anInterface> member) {
this.member = member;
}
}
我的問題是:我怎么稱呼thisThing
構造函數?
為了調用thisThing
的構造方法,您需要定義一個首先實現anInterface
的類:
class ClassForThisThing implements anInterface {
... // interface methods go here
}
現在,您可以如下實例化thisThing
:
thisThing theThing = new thisThing(ClassForThisThing.class);
此類實例化背后的想法通常是給thisThing
一個類,通過該類可以通過反射創建anInterface
實例。 編譯器確保傳遞給構造函數的類與anInterface
兼容, anInterface
確保像這樣進行強制轉換
anInterface memberInstance = (anInterface)member.newInstance();
將始終在運行時成功。
我不喜歡你做了什么。
為什么不呢? 這里不需要泛型。 您只是在作曲。 傳遞實現AnInterface
任何引用。 Liskov替代原則表示一切正常。
public class ThisThing {
private AnInterface member;
public ThisThing(AnInterface member) {
this.member = member;
}
}
這是界面:
public interface AnInterface {
void doSomething();
}
這是一個實現:
public class Demo implements AnInterface {
public void doSomething() { System.out.println("Did it"); }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.