用动态泛型类型测试Java泛型

诱导素

我正在编写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

我的问题是-上面的代码有什么错误,应该怎么做?

罗希特·贾恩(Rohit Jain)

您需要在使用该方法之前声明该类型的参数。要创建泛型方法,请在返回类型之前声明type参数:

private <T> void assertIteratorThrowsNoSuchElement(Deque<T> deque, Class<T> cl) {
}

另外,我看不到第二个参数的任何使用您甚至都没有使用它。T从您传递的实际类型中自动推断出type参数如果为此添加了它,则可以将其删除。只要保持在1的参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章