gpt4 book ai didi

java - 通过封闭类类型变量绑定(bind)的内部类类型参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:02:37 24 4
gpt4 key购买 nike

有什么方法可以将封闭类声明的类型变量用作内部类中声明的类型变量的绑定(bind)?

class Test<E> {
class Inner<T extends E> {}
<T extends E> void doStuff(T arg) {}
public static void main(String[] args) {
new Test<Number>().doStuff(new Integer(0)); // works fine, as expected
new Test<Number>().new Inner<Integer>(); // won't compile
}
}

javac 给出了这个错误:

Test.java:6: type parameter java.lang.Integer is not within its bound
new Test<Number>().new Inner<Integer>();
^

我找不到能满足编译器要求的任何类型组合。 Inner 声明的类型参数 TdoStuff 之间有什么区别?为什么一个有效而另一个无效?

我不是在寻找替代方案,我只是想更好地了解该语言的工作原理。

最佳答案

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6557954

Bug ID: 6557954
Votes 2
Synopsis Inner class type parameters doesn't get substituted when checking type well-formedness
Category java:compiler
Release Fixed 7(b40)
State 10-Fix Delivered, bug
Priority: 5-Very Low
Submit Date 16-MAY-2007
Posted Date : 2008-07-02 16:22:46.0

说明

The compiler fails to accept this program:

class Foo<T> {
class Bar<U extends T> {}
Foo<Number>.Bar<Integer> f;
}

评价

This is a problem in Check.java as when checking for bound-conformance actual type parameters are subsituted only in topmost type-variable's bound. In this case we have that Foo.Bar is to be checked against the actual type-parameters T=Number, U=Integer

So it should be the case that:

Number <: Object
Integer <: [Number/T]T = Number

unfortunately, javac misses the second substitution so that the check becomes:

Integer <: T 

which is wrong and cause the error.

编辑:

在我的系统上,问题中的代码使用 Java 7 javac 编译没有错误:

C:\workspace\Sandbox\src>"%JAVA_HOME%\bin\javac.exe" -version
javac 1.7.0-ea

但是它失败了,出现了 Java 6 javac 问题中指出的错误:

C:\workspace\Sandbox\src>"%JAVA_HOME%\bin\javac.exe" -version
javac 1.6.0_17

关于java - 通过封闭类类型变量绑定(bind)的内部类类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4823278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com