为什么要编译?该代码似乎正在打破对类型参数的约束
-
15-10-2019 - |
题
在以下测试中,Testerclass对其两个类型参数之间的关系构成了约束。方法func2()似乎打破了该约束,我希望它会在某处引起键入汇编错误(在Func2的定义上,或每当类与字符串以外的任何第二个参数一起使用时),但事实并非如此!
此外,如果我调用func2并将结果保存在适当键入的变量中,则汇编失败(在该变量的类型上)。但是,尽管事实在两种情况下(在上铸之前),但要做同样的事情并保存更通用的类型(例如对象)都成功了。
这里发生了什么?
谢谢!
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 Compiler)错误。
我已经为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
不隶属于 StackOverflow