私は Java ジェネリックに関して少し奇妙な問題を抱えています。実際にはまったく問題にならないかもしれませんし、設計でジェネリックを間違って使用しようとしているのは私だけかもしれません。申請書の詳細はすべてお伝えしません (無関係で退屈です)。
問題の本質を捉えた小さなスニペットを作成しました。
このような Producer インターフェイスがあります。
public interface Producer<P> {
public P produce();
}
このように見えるこのインターフェースの実装があります
public class IntegerProducer<P> implements Producer<P> {
@Override
public P produce() {
return (P)new Integer(10);
}
}
私がプロデュースメソッドで本当にする必要があるのは、次のようなものです
if (P instanceOf Integer) return (P)new Integer(10);
else throw new Exception("Something weird happened in the client app");
もちろん、P instanceOf Integer は機能しません。しかし、私がやろうとしていることの本質を理解している場合は、解決策を共有してください.
助けてくれてありがとう。
明確化 1: 問題は、整数のみを返したいということではありません。問題は、関数 Produce() で、クライアント プログラムが使用するジェネリックの型を確認し、それに基づいて関数の動作を変更する必要があることです。特定のタイプのオブジェクト (ワイルドカードを使用できた場合) に使用されるジェネリックのタイプを制限したいということではありませんが、ジェネリックで使用されるオブジェクトの種類に基づいて、関数 Produce() の動作が少し異なる必要があります。クライアントコード。