[英]java testing generics with dynamic generic type
我正在編寫junit3測試。 我想創建一個通用測試方法(下面的assertIteratorThrowsNoSuchElement
),可以將我的通用結構作為第一參數,並將通用類型作為第二參數。 那是因為我想檢查一次是否為字符串正確拋出了異常,然后為整數正確拋出了異常,對於我自己的自定義類型再次拋出了異常。 這是我現在得到的代碼:
public void testEmptyIteratorException () {
Deque<String> deque = new Deque<String>();
assertIteratorThrowsNoSuchElement(deque, String.class);
}
private void assertIteratorThrowsNoSuchElement(Deque<T> deque, Class<T> cl) {
Iterator<T> iter = deque.iterator();
try {
iter.next();
fail();
} catch (NoSuchElementException expected) {
assertTrue(true);
}
}
編譯器不喜歡:
The method assertIteratorThrowsNoSuchElement(Deque<T>, Class<T>) from the type DequeTest refers to the missing type T // the first method
Multiple markers at this line // the second method
- T cannot be resolved to a type
- T cannot be resolved to a type
我的問題是-上面的代碼有什么錯誤,應該怎么做?
您需要在使用之前聲明該方法的類型參數。 要創建泛型方法,請在返回類型之前聲明type參數:
private <T> void assertIteratorThrowsNoSuchElement(Deque<T> deque, Class<T> cl) {
}
另外,我看不到第二個參數的任何使用。 您甚至都沒有使用它。 類型參數T
是根據您傳遞的實際類型自動推斷出來的。 如果為此目的添加了它,則可以將其刪除。 只要保持在1 日的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.