簡體   English   中英

如何檢查方法的通用返回類型是否與通過參數傳遞的 class 匹配?

[英]How to check if the generic return type of a method matches the class passed via parameter?

我有一個Map存儲名為DAO的超級 class 的實例。 用戶可以將這個DAO class的不同子類放入map。 The keys of the map are the Class of the corresponding model (ie Apple.class ), which are also stored as instance variable in the DAO object. 然后可以通過使用 generics 並將DAO轉換為所需子類型的 getter 來檢索DAO實例。

Map<Class<? extends Model>, DAO> daoMap = new HashMap<>();


// Create and store DAOs
SearchDAO<Apple> appleDAO = new SearchDAO<>(Apple.class);
daoMap.put(Apple.class, appleDAO);
CrudDAO<Orange> orangeDAO = new CrudDAO<>(Orange.class);
daoMap.put(Orange.class, orangeDAO);


// Method to retrieve DAOs
@SuppressWarnings("unchecked")
public <T extends DAO> T getDAO(Class<? extends Model> modelClass) {
    return (T) daoMap.get(modelClass);
}

要檢索 DAO,您只需執行以下操作:

final SearchDAO<Apple> appleDAO = this.getDAO(Apple.class);

這工作正常,但現在我想要一個檢查,當存儲的 DAO 中的 model class 不等於T時會引發異常。 即以下內容在執行時應該拋出異常:

final SearchDAO<Orange> orangeDAO = this.getDAO(Apple.class);

如前所述, Class類型也存儲在DAO本身中。 所以我想要這樣一張支票:

@SuppressWarnings("unchecked")
public <T extends DAO> T getDAO(Class<? extends Model> modelClass) {
    T dao = (T) daoMap.get(modelClass);
    if(!dao.getModelClass() instancof T) {
       throw new IllegalStateException("Apples are not Oranges!");
    }
    return dao;
}

這可能嗎? 感謝您的任何建議!

這工作正常,但現在我想要一個檢查,當存儲的 DAO 中的 model class 不等於 TIe 時引發異常,以下應在執行時引發異常:

T is something that extends DAO so the model class is never equal to T , as model class is something that extends Model .

If you want to make sure that the DAO which is stored in the map under a model class key eg Apple.class has the same modelClass instance stored, you could do it like this:

 @SuppressWarnings("unchecked")
 public <T extends DAO> T getDAO(Class<? extends Model> modelClass) {
    T dao = (T) daoMap.get(modelClass);
    if(!dao.getModelClass().isAssignableFrom(modelClass)) {
         throw new IllegalStateException("Apples are not Oranges!");
    }
    return dao;
 }

if you now put a DAO instance with the model class Apple.class in the map under the Orange.class key:

SearchDAO<Apple> appleDAO = new SearchDAO<>(Apple.class);
daoMap.put(Apple.class, appleDAO);
daoMap.put(Orange.class, appleDAO);

你要橘子:

final SearchDAO<Orange> orangeDAO = getDAO(Orange.class);

你得到:

java.lang.IllegalStateException: Apples are not Oranges!

如果這是您想要的,您還可以考慮在將DAO實例放入 map 時執行檢查,如果鍵 class 與DAO的 modelClass 不同,則拋出異常。

暫無
暫無

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

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