java 编译参数_java – 为什么要编译?代码似乎打破了类型参数的约束
在下面的測(cè)試中,TesterClass對(duì)其兩個(gè)類型參數(shù)之間的關(guān)系設(shè)置了約束.方法func2()似乎打破了這個(gè)約束,我希望它會(huì)在某處導(dǎo)致類型編譯錯(cuò)誤(在func2的定義中,或者每當(dāng)類與String之外的任何第二個(gè)參數(shù)一起使用時(shí)),但它不會(huì)!
此外,如果我調(diào)用func2并將結(jié)果保存在適當(dāng)類型的變量中,則編譯失敗(在該變量的類型上).但是做同樣的事情并保存在更通用的類型(例如Object)中會(huì)成功,盡管事實(shí)上函數(shù)的返回類型在兩種情況下都應(yīng)該具有相同的類型(在向上轉(zhuǎn)換之前).
這里發(fā)生了什么?
謝謝!
public class TestGenerics {
public static class ParamedType {}
public class TesterClass, B> {
public TesterClass func() {
return new TesterClass();
}
public TesterClass func2() {
return new TesterClass();
}
}
public Object test() {
// How can I use these type parameters? Doesn't .func2 now have an invalid return type?
TesterClass,Integer> testClass = new TesterClass, Integer>();
//TesterClass, Integer> res2 = testClass.func2(); //
Object res = testClass.func2(); // Compiles
return res;
}
}
編輯:這不能在javac中編譯(下面報(bào)告的版本).我正在使用Eclipse,并試圖找出實(shí)際運(yùn)行的編譯器是什么.會(huì)更新.可能是JDT(Eclipse編譯器)錯(cuò)誤.
解決方法:
簡(jiǎn)單回答:它不能編譯,至少在javac 1.7下:
Test.java:10: type parameter A is not within its bound
public TesterClass func2() {
^
where A,B are type-variables:
A extends ParamedType 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();
^
where A,B are type-variables:
A extends ParamedType declared in class Test.TesterClass
B extends Object declared in class Test.TesterClass
2 errors
你沒(méi)有說(shuō)你在編譯它是什么 – 我的猜測(cè)是你的Java編譯器有一個(gè)錯(cuò)誤.
標(biāo)簽:java,eclipse,compiler-bug,generics,eclipse-jdt
來(lái)源: https://codeday.me/bug/20190531/1188938.html
總結(jié)
以上是生活随笔為你收集整理的java 编译参数_java – 为什么要编译?代码似乎打破了类型参数的约束的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 3DSMAX和ZBRUSH打造神秘性感美
- 下一篇: restful处理