簡體   English   中英

Java方法中的嵌套泛型?

[英]Nested generics in Java methods?

我正在創建自己的MVP框架,並且遇到了泛型的麻煩。

我的演示者是這樣定義的,內部類包含對子元素的引用,這些子元素也是通用演示者:

public abstract class Presenter<TView extends View, TKey extends Key>
{
    protected final HashMap<String, StageInstances<?, ?>>   _stages;

    public <TChildView extends View, TChildKey extends Key> void addStage(Class<Presenter<TChildView, TChildKey>> stage, String name)
    {
        _stages.put(name, new StageInstances<TChildView, TChildKey>(stage));
    }

    // ...

    protected class StageInstances<TChildView extends View, TChildKey extends Key>
    {
        protected Class<Presenter<TChildView, TChildKey>>       _presenter;
        protected HashMap<Key, Presenter<TChildView, TChildKey>>    _instances;

        public StageInstances(Class<Presenter<TChildView, TChildKey>>   presenter)
        {
            _presenter = presenter;
            _instances = new HashMap<Key, Presenter<TChildView, TChildKey>>();
        }

        public Presenter<?, ?> getInstance(Key key)
        {
            if (!_instances.containsKey(key))
            {
                try
                {
                    _instances.put(key, _presenter.newInstance());
                } catch (Exception e)
                {
                    e.printStackTrace();

                    return null;
                }
            }

            return _instances.get(key);
        }
    }
}

我對此有一個具體的實現

public class ResultsPresenter extends Presenter<ResultsView, Results>

public class SearchPresenter extends Presenter<SearchView, StringKey>
{
    // ...

    public void bind()
    {
        addStage(ResultsPresenter.class, "results");
    }
}

其中ResultsView,SearchView擴展了View和Results,StringKey實現了Key

方法addStage(...)引發以下編譯時錯誤:

**The method addStage(Class<Presenter<TChildView,TChildKey>>, String) in the type 
Presenter<SearchView,StringKey> is not applicable for the arguments 
(Class<ResultsPresenter>, String)**

任何幫助或更好的做法,將不勝感激

嘗試將方法原型更改為:

public <TChildView extends View, TChildKey extends Key> void addStage(Class<? extends Presenter<TChildView, TChildKey>> stage, String name)

注意我將Class<Presenter<TChildView, TChildKey>>更改為Class<? extends Presenter<TChildView, TChildKey>> Class<? extends Presenter<TChildView, TChildKey>> 這將允許您傳遞Presenter的子類的類,而不是Presenter本身。

我沒有親自嘗試過,但出於直覺,我會說

addStage(Class<Presenter<TChildView, TChildKey>> stage, String name)

應該

addStage(Class<Presenter<? extends TChildView,? extends TChildKey>> stage, String name)

首先嘗試Alex建議。 使代碼更具可讀性,並且比我的更有意義。 如果兩者均失敗,則將它們合並。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM