[英]How to use class type passed as parameter to method to define local variables
[英]How to define type constraint on parameter of method?
我有A
類和接口B
,以及一個方法:
void foo(A x) {}
我想要的是在參數x
上定義一個必須實現接口B
的約束。
雖然我知道它可以在運行時完成,例如:
void foo(A x) {
if (!(x instanceof B)) {
throw new IllegalStateException();
}
}
或者定義另一個類和alter方法簽名,如:
class C extends A implements B {}
void foo(C x) {}
我不接受這個解決方案,因為在我的情況下,我在第三方jar中有很多A
子類,我不想修改它們。
我想知道它是否可以在語言級別上實現,在我編寫調用代碼時即時啟用該約束。
如果必須這樣做,您可以使用泛型,如有界類型參數文檔,“多個邊界”部分中所述:
public interface A {}
public interface B {}
public static class C implements A, B {}
public static <T extends A & B> void foo(T type) {
}
public static void main(String[] args) {
foo(new A() {}); // compile error
foo(new B() {}); // compile error
foo(new C() {});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.