簡體   English   中英

通過泛型在Java中創建泛型接口

[英]Making generic interface in java through generics

我正在使用以下界面,如下所示

public interface ZaestrorardRule {

    Map<String, List<MMTM>> exceute(String jobCode, String Plientlo) throws AaestroRardNetworkException;

}

然后有一個實現它的類,如下所示

public class AaestroRardBusinessRNFRuleImpl implements ZaestrorardRule {

    public Map<String, List<MMTM>> exceute(String jobCode, String Plientlo) throws AaestroRardNetworkException {

    }

}

現在讓我們說除了上面顯示的ZaestrorardRule之外,我還在其他功能上,ZaestrorardRule具有與ZaestrorardRule相同的功能,然后我必須創建一個單獨的界面,如下所示

public interface WWaestrorardRule {

    Map<String, List<MMTM>> exceute(String jobCode, String Plientlo) throws AaestroRardNetworkException;

}

我的查詢是,我可以在接口中使用泛型嗎,因為接口的結構是固定的,所以只有一個接口。

在Java中,我們可以擴展接口。 您可以創建一個父接口:

public interface GenericRule {

    Map<String, List<MMTM>> exceute(String jobCode, String Plientlo) throws AaestroRardNetworkException;

}

像這樣更改兩個界面

public interface ZaestrorardRule extends GenericRule {

}

public interface WWaestrorardRule extends GenericRule {

}

正如問題注釋中的結論,由於兩個接口都具有相同的參數和返回類型,因此實際上不需要創建通用接口。 相反,您要做的是:

public interface Rule {

    Map<String, List<MMTM>> execute(String s1, String s2) throws YourException;

}

然后您有Rule不同實現

public class ZaestrorardRule implements Rule {
    // implement interface
}

public class WWaestrorardRule implements Rule {
    // implement interface
}

這就是應該使用接口的方式。


如果您需要其他參數類型或返回類型,則可以開始使用泛型。 您的接口已經類似於java.util.function.BiFunction不同之處在於它引發了一個自定義異常(最有可能是已檢查的異常)。 只需執行BiFunction操作即可:

public interface Rule<T, U, R> {
    R execute(T t, U u) throws YourException;
}

如果兩個參數將始終為同一類型,則可以通過將接口聲明為Rule<T, R>並將方法聲明為R execute(T t1, T t2) throws YourException

暫無
暫無

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

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