POJOでジェネリックを使用します

learningMyWayThru:

私は、ジェネリックを使用して、入力に応じて、メソッドから複数の異なるPOJOオブジェクト応答を戻したいです。POJOのは、完全に独立したPOJOあるすなわち階層の一部ではありません

//POJO1
class A1  implements Serializable {

   // Instance variable with getter and setter

}

//POJO2
class B1 implements Serializable {

  // Instance variable with getter and setter

}


class XYZ {

   private ObjA objA;
   private ObjB objB;

   public <T>Optional<T>  getResponse(String input) {


       if(input.equals("A")) {       
           return objA.getResponse();  // This returns an optional of POJO A1 or Optional.empty()
       } else {
           return objB.getResponse();  // This returns an optional of POJO B1 or Optional.empty()
       }
   }
}

しかし、私はエラーを取得します Incompatible types. Required Optional<T> but 'of' was inferred to Optional<T>: no instance(s) of type variable(s) exist so that A1 conforms to T inference variable T has incompatible bounds: equality constraints: T lower bounds: A1

私はPOJOクラス定義に一般的なタグを付けてみましたが、無駄に。誰かがどこ私はここで間違っているつもりです指摘していただけますか?

ジョーンVernee:

問題は、コンパイル時の型ができるようにしようとしているということであるTの実行時の値に依存inputできません。値が動的であるので、あなたは正しいアプローチが使用することですので、返されるタイプを知ることができませんOptional<?>

public Optional<?>  getResponse(String input) {
   if(input.equals("A")) {       
       return objA.getResponse();  // This returns an optional of POJO A1 or Optional.empty()
   } else {
       return objB.getResponse();  // This returns an optional of POJO B1 or Optional.empty()
   }
}

値が場合input されて静的に知られている、あなたは別の戻り値の型を持つ2つの方法を作成することができます。

public Optional<A1> getResponseA1() {
    return objA.getResponse();
}

public Optional<B1> getResponseB1() {
    return objB.getResponse();
}

そして、例えば、代わりに文字列を渡すのそれらのいずれかを呼び出します。

// Optional<?> result = xyz.getResponse("A"); // Not this
Optional<A1> result = xyz.getResponseA1(); // But this

それとも、両方のアプローチを使用して、発信者は、彼らが文字列かどうかの値を知っていればに基づいて使用するかを決定させことができます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=119230&siteId=1