パラメータを汎用メソッドに渡す際に問題があります。 「eventManager.setTarget(この);」Java Genericsメソッドのパラメータ渡しの問題
public class View<T extends View<T,PM>, PM extends Source> {
protected PM source;
protected EventManager<T, PM> eventManager;
public View(PM s){
this.source = s;
eventManager = new EventManager<T, PM>();
eventManager.setTarget(this); //error: "The method setTarget(T) in the type
//EventManager<T,PM> is not applicable for the arguments (View<T,PM>)"
eventManager.setSource(s);
}
public void setBinding(Topic topic, IEventAction<T,PM> action){
eventManager.setEventAction(topic, action)
}
}
/**
* EventManager class has to remain completely generic. The type parameters cannot "extends"
* anything because the EventManager is used also in other parts where T and S will have to be
* classes other than "View" and "Source"
*/
public class EventManager<T, S> {
protected T target;
protected S source;
private LinkedHashMap<Topic, IEventAction<T, S>> eventActions;
public EventManager(T target, S source){
this.target = target;
this.source = source;
}
public void setTarget(T target){
this.target = target;
}
public void setSource(S source){
this.source = source;
}
public void setEventAction(Topic topic, IEventAction<T, S> action) {
//some code here ...
omissis...
eventActions.put(topic, action);
omissis...
}
//other methods down here...omissis
}
Eclipseは私が行にコメントを入れ、エラーを与える:コードは次のようです。なぜこのエラーが出るのか理解できません。 とにかく、解決策を見つけました(明らかに)が、私は "きれいな"か "汚い"かどうかはわかりません。この解決策は次のとおりです。
eventManager.setTarget((T)this);
しかし、「タイプの安全性:ビューからTへのキャストをチェックしない」という警告が表示されます。警告を消去するために、私はコンストラクタメソッドの上に次のものを置く:
@SuppressWarnings("unchecked")
これはうまくいかず、何が問題なのでしょうか?別の「クリーナー」ソリューション(存在する場合)をお持ちですか?これは「汚い」アプローチだと思いますか?
どんな騒ぎも大歓迎です。
、「これは」コンストラクタからより多くのように、良い習慣ではありませんへの参照をさせる:
一般的に、ここでのアプローチは、クラスが抽象的にし、抽象
getThis
方法を追加することです並行して文脈で。 – Scorpion私の答えを読んでも分かりませんが、何の理由もないジェネリックを使用している可能性があります。私はあなたの授業で何をしているのかについて詳しくは分かっていないので、それが本当かどうかは分かりません。 – toto2
@Scorpion 原則として、私は "this"の使用についてあなたが言ったことに絶対に同意します。しかし、私の特別なケースでは、EventManagerへの参照を割り当てるだけで使用されます。 「View」オブジェクトが完全に作成される前に、その参照を使用するものは他にありません。ちなみに、EventManagerを使用する唯一のオブジェクトはViewです。このため、私は安全な状態です。 – user1085876