0

Class A以下でコンパイルできないのは何が問題なのですか?

public class GenericsHell {
   interface Shape{} 
   interface Circle extends Shape {} 

   interface ShapeHelper<T extends Shape> {
      void draw(T shape);
   }

   class A<T extends Shape> {
      A(T shape, ShapeHelper<? extends Shape> helper) {
         helper.draw(shape); // Issues not-applicable argument error 
      }
   }

   class B {
      B(Circle circle, ShapeHelper<Circle> helper) {
         helper.draw(circle);
      }
   }
}   

Eclipse で次のエラーが発生します。

The method draw(capture#1-of ? extends Shape) in the type ShapeHelper<capture#1-of ? extends Shape> is not applicable for the arguments (T)

4

5 に答える 5

3

クラス A の汎用パラメーターを 1 つのものとして定義しましたが、コンストラクターで互換性のない方法で使用しようとしました (<T extends Shape>は と同じではありません<? extends Shape>。コードをコンパイルして、既に定義されている汎用パラメーターを一貫して使用するように変更します。

class A<T extends Shape> {
    public A(T shape, ShapeHelper<T> helper) {
        helper.draw(shape);
    }
}

余談ですが、あなたのコードは、質問で示したエラー メッセージを生成しません。むしろ、次のようになります。

GenericsHell.ShapeHelper 型のメソッド draw(capture#1-of ? extends GenericsHell.Shape) は、引数 (T) には適用されません。

于 2012-01-22T15:18:10.790 に答える
2

タイプ GenericsHell.ShapeHelper<capture#1-of ? の draw(capture#1-of ? extends GenericsHell.Shape) メソッド extends GenericsHell.Shape> は引数に適用されません (T)

問題は、あなたの宣言では形状が T 型ですが、 <? 型の ShapeHelper を要求していることです。これは、S と T が異なる ShapeHelper を引数として渡すことができることを意味します。

helper<S>.draw(shape<T>);次に、意味をなさない呼び出しを行います。

このメソッドの正しい実装は次のようになります。

class A<T extends Shape> {
  A(T shape, ShapeHelper<T> helper) {
    helper.draw(shape); 
  }
}

これにより、形状と形状ヘルパーが互換性のある型であることが保証されます。

于 2012-01-22T15:27:18.090 に答える
1

への通話を確認することは重要Aです。しかし、あなたは次のようなことをしたようA<Integer>です。ただし、クラス宣言に従ってT拡張する必要があります..そうではありません。したがって、に変更するか、 toであるタイプを提供しますShapeInteger<? extends Shape><T>ShapeA

于 2012-01-22T15:20:48.457 に答える
0

PECS (生産者extends、消費者super) を思い出してください。

helperはコンシューマー (何かを渡す) であるため、 にすることはできませんextends。おそらくそれは可能性がありますがsuper、この場合それが意味をなすかどうかはわかりません

于 2012-01-22T22:45:18.400 に答える
0

代わりにこれを試してください:

class A<T extends Shape> {
    A(T shape, ShapeHelper<T> helper) {
        helper.draw(shape);
    }
}
于 2012-01-22T15:24:03.220 に答える