gpt4 book ai didi

Java 泛型 : vs 捕获

转载 作者:行者123 更新时间:2023-12-02 07:20:39 24 4
gpt4 key购买 nike

我正在尝试模拟 ScheduledExecutorService,但我在使用泛型时遇到了麻烦。

这是一个片段:

ScheduledFuture<?> future = mock(ScheduledFuture.class);

ScheduledExecutorService scheduledExecutorService =
Mockito.mock(ScheduledExecutorService.class);

when(scheduledExecutorService.schedule(Mockito.any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(future);

这不会编译并出现以下错误:

Error:(20, 109) java: no suitable method found for 
thenReturn(java.util.concurrent.ScheduledFuture<capture#1 of ?>)
method org.mockito.stubbing.OngoingStubbing.thenReturn(java.util.concurrent.ScheduledFuture<capture#2 of ?>) is not applicable
(argument mismatch; java.util.concurrent.ScheduledFuture<capture#1 of ?> cannot be converted to java.util.concurrent.ScheduledFuture<capture#2 of ?>)
method org.mockito.stubbing.OngoingStubbing.thenReturn(java.util.concurrent.ScheduledFuture<capture#2 of ?>,java.util.concurrent.ScheduledFuture<capture#2 of ?>...) is not applicable
(argument mismatch; java.util.concurrent.ScheduledFuture<capture#1 of ?> cannot be converted to java.util.concurrent.ScheduledFuture<capture#2 of ?>)

如果我在声明 ScheduledFuture 时不使用泛型,它会在编译时出现警告。

 ScheduledFuture future 

有什么正确的方法吗?我的意思是,有没有我可以使用的通配符,这样它就可以在没有警告的情况下进行编译?

最佳答案

以下工作类型正确:

<T> ScheduledFuture<?> thenReturnMockFuture(
OngoingStubbing<ScheduledFuture<T>> stubbing) {
// Declare a local abstract class, so that future is type-correct.
abstract class ScheduledFutureT implements ScheduledFuture<T> {}
ScheduledFuture<T> future = mock(ScheduledFutureT.class);

stubbing.thenReturn(future);
return future;
}

然后这样调用:

ScheduledExecutorService scheduledExecutorService = 
mock(ScheduledExecutorService.class);

ScheduledFuture<?> future =
thenReturnMockFuture(
when(scheduledExecutorService.schedule(...)));

我想你也可以这样做(没有方法,但有抽象本地类):

ScheduledFuture<?> future = mock(ScheduledFutureT.class);
doReturn(future).when(scheduledExecutorService).schedule(...);

注意 the caveatdoReturn不是类型安全的,所以你只需要确保你正在调用一个确实返回 ScheduledFuture<?> 的方法。 .

关于Java 泛型 : <? > vs 捕获<?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116539/

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