2017-01-16 17 views
0

ここでは、私が取り組んでいるオブジェクトモデルの簡略化されたバージョンを示します。ジェネリック編集エラー:型引数が型変数の境界内にないS

public class GenericsTest { 
    public interface FooInterface { 
     public void foo(); 
    } 
    public class Bar implements FooInterface { 
     public void foo() {} 
    } 
    public interface GenericInterface <T> { 
     public T func1(); 
    } 
    public class Service implements GenericInterface<Bar> { 
     @Override 
     public Bar func1() { 
      return null; 
     } 
    } 
    public class GenericBar <S extends GenericInterface<FooInterface>> { 
     public S s; 
     public GenericBar() {} 
    } 

    public static void main(String[] args) { 
     GenericBar<Service> serviceGenericBar; // <-- compilation error at this line 

     <... more code ...> 
    } 

} 

コンパイラエラー:type argument GenericsTest.Service is not within bounds of type-variable S

IDE(IntelliJのは)エラーのいくつかの詳細を示していますType parameter 'GenericsTest.Service' is not within its bound; should implement GenericsTest.GenericInterface<GenericTests.FooInterface>

ServiceクラスはGenericInterfaceを実施しています。私は同じエラーでいくつかの他のSOの質問を見てきましたが、この特定のシナリオの手がかりを提供していません。どのようにこれを修正するための任意のアイデア?

+0

GenericBarインプリメンテーションを共有する – StackFlowed

答えて

2

問題は2つのコンパイラがあなたに言っているまさにです:タイプServiceをタイプがSであるタイプGenericBarが必要な範囲内にありません。具体的には、GenericBarは、その実現のSパラメータをGenericInterface<FooInterface>に拡張するタイプにバインドする必要があります。 Serviceはその要件を満たしていません。

ServiceはどちらGenericInterface<FooInterface>もそのタイプの延長、そのBar実装FooInterfaceにもかかわらず、事実である、GenericInterface<Bar>を実装しています。基本的には同じ理由でをタイプList<Object>の変数に代入することはできません。

あなたがそうのようなクラスGenericBarの定義を変更することによって、コンパイルエラーを解決することができます

public class GenericBar <S extends GenericInterface<? extends FooInterface>> { 
    public S s; 
    public GenericBar() {} 
} 

これはあなたが実際にを使用したいものであるかどうかは、あなたが答えることができる全く別の問題です。

+0

はい 'Bar'タイプのみを扱うには' Service'クラスが必要です。説明ありがとう。 – mpprdev

0

サービスを変更してGenericInterfaceを実装すると、コードがコンパイルされます。

public class Service implements GenericInterface<FooInterface> { 
    @Override 
    public Bar func1() { 
     return null; 
    } 
} 

それともあなただけのバーのベースにサービスを制限することを好む場合、それはより一般的になりますので、あなたがGenericBarを変更することができます:

public class Service implements GenericInterface<Bar> { 
    @Override 
    public Bar func1() { 
     return null; 
    } 
} 

public class GenericBar<S extends GenericInterface<? extends FooInterface>> { 
    public S s; 

    public GenericBar() { 
    } 
} 
関連する問題