2011-01-27 8 views
3

内部クラスで宣言された型変数の囲みとして囲むクラスで宣言された型変数を使用する方法はありますか?内部クラスの型パラメータを囲むクラス型変数でバインド

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との違いは何ですか?なぜ、1つは動作し、もう1つは動作しませんか?

私は代わりの方法を探していません。言語の仕組みをよりよく理解したいと思っています。

+1

この例はコンパイルされ、私のために書かれたとおりに正常に動作します。 – ILMTitan

+1

@ILMTitanどのコンパイラを使用していますか? – gdejohn

+1

はjavac 1.6.0_21で失敗します。 – axtavt

答えて

3

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 
+0

だから、それはJava 7で修正されていますか? – gdejohn

+1

@Charlatan - それは私がそれを読む方法です。私は自分のシステムでも確認しました。私の編集を参照してください。 –

関連する問題