gpt4 book ai didi

java测试具有动态泛型类型的泛型

转载 作者:行者123 更新时间:2023-11-29 03:24:24 24 4
gpt4 key购买 nike

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

我的问题是 - 上面代码中的错误是什么以及应该如何完成?

最佳答案

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

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

此外,我没有看到那里使用了 2nd 参数。你甚至没有使用它。类型参数 T 是根据您传递的实际类型自动推断出来的。如果您为此目的添加了它,则可以将其删除。只需保留 1st 参数即可。

关于java测试具有动态泛型类型的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21809341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com