我在通用函式中遇到了類層次結構的問題。我需要強制執行,使用兩個類T并U在函式中指定,一個是另一個的孩子。我驚訝地發現,該構造<T extends U>根本不強制執行Uand的父子關系T。相反,它也允許T和U是同一型別。
這會產生一個問題,因為在這種情況下,Java 似乎U extends T不會指示錯誤,而是會愉快地將兩個物件都推斷為型別T(這無疑是正確的),然后編譯并運行代碼而沒有任何抱怨。
這是一個說明問題的示例:
public class MyClass {
public static void main(String args[]) {
Foo foo = new Foo();
Bar bar = new Bar();
// This code is written as intended
System.out.println( justTesting(foo, bar) );
// This line shouldn't even compile
System.out.println( justTesting(bar, foo) );
}
static interface IF {
String get();
}
static class Foo implements IF {
public String get(){return "foo";}
}
static class Bar extends Foo {
public String get(){return "bar";}
}
static <G extends IF , H extends G> String justTesting(G g, H h) {
if (h instanceof G)
return h.get() " (" h.getClass() ") is instance of " g.getClass() ". ";
else
return "it is the other way round!";
}
}
這是輸出:
bar (class MyClass$Bar) is instance of class MyClass$Foo.
foo (class MyClass$Foo) is instance of class MyClass$Bar.
我需要確保編譯器觀察到泛型類的父子關系。有沒有辦法做到這一點?
uj5u.com熱心網友回復:
它可以編譯,因為和都是IF“上限” 。 H G
意味著:泛型并不像我們想象的那樣“動態”,我們也可以這樣寫:
static <G extends IF, H extends IF> ... // just pointing out that G *could* differ from H
無視空檢查,這是你想要的:
static <G extends IF, H extends G> String justTesting(G g, H h) {
if (g.getClass().isAssignableFrom(h.getClass())) {
return h.get() " (" h.getClass() ") is instance of " g.getClass() ". ";
} else {
return "it is the other way round!";
}
}
?
Class.isAssignableFrom()
印刷:
bar (class com.example.test.generics.Main$Bar) is instance of class com.example.test.generics.Main$Foo.
it is the other way round!
并注意“匿名課程”,例如:
System.out.println(
justTesting(
new IF() {
@Override
public String get() {
return "haha";
}
}, foo)
);
System.out.println(
justTesting(
foo, new IF() {
@Override
public String get() {
return "haha";
}
}
)
);
print both "it is the other way round!",所以這里的決定不是那個“二進制”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412128.html
標籤:
