簡體   English   中英

為什么編譯?代碼似乎打破了類型參數的約束

[英]Why does this compile? The code seems to be breaking constraints on the type parameters

在下面的測試中,TesterClass對其兩個類型參數之間的關系設置了約束。 方法func2()似乎打破了這個約束,我希望它會在某處導致類型編譯錯誤(在func2的定義中,或者每當類與String之外的任何第二個參數一起使用時),但它不會!

此外,如果我調用func2並將結果保存在適當類型的變量中,則編譯失敗(在該變量的類型上)。 但是做同樣的事情並保存在更通用的類型(例如Object)中會成功,盡管事實上函數的返回類型在兩種情況下都應該具有相同的類型(在向上轉換之前)。

這里發生了什么?

謝謝!

public class TestGenerics {
    public static class ParamedType<T> {}


    public class TesterClass<A extends ParamedType<B>, B> {
        public TesterClass<A, B> func() {
            return new TesterClass<A, B>();
        }

        public TesterClass<A, String> func2() {
            return new TesterClass<A, String>();
        }
    }

    public Object test() {
        // How can I use these type parameters? Doesn't .func2 now have an invalid return type?
        TesterClass<ParamedType<Integer>,Integer> testClass = new TesterClass<TestGenerics.ParamedType<Integer>, Integer>();

        //TesterClass<ParamedType<String>, Integer> res2 = testClass.func2(); // <-- will not compile
        Object res = testClass.func2(); // Compiles
        return res;
    }
}

編輯 :這不能在javac中編譯(下面報告的版本)。 我正在使用Eclipse,並試圖找出實際運行的編譯器是什么。 會更新。 可能是JDT(Eclipse編譯器)錯誤。

我已經為eclipse的jdt打開了一個錯誤報告: https ://bugs.eclipse.org/bugs/show_bug.cgi id = 333503

簡單回答:它不能編譯,至少在javac 1.7下:

Test.java:10: type parameter A is not within its bound
    public TesterClass<A, String> func2() {
                       ^
  where A,B are type-variables:
    A extends ParamedType<B> declared in class Test.TesterClass
    B extends Object declared in class Test.TesterClass
Test.java:11: type parameter A is not within its bound
        return new TesterClass<A, String>();
                               ^
  where A,B are type-variables:
    A extends ParamedType<B> declared in class Test.TesterClass
    B extends Object declared in class Test.TesterClass
2 errors

你沒有說你在編譯它是什么 - 我的猜測是你的Java編譯器有一個錯誤。

顯然,這是JDT.core中的Eclipse錯誤。 我在https://bugs.eclipse.org/bugs/show_bug.cgi?id=333503上打開了一個錯誤報告

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM