泛型Java错误:不兼容类型:不存在类型变量T的实例,因此可选<T>符合Iterable<AvailableLicence>
通常我是一名C#开发人员,但我尝试用Java编写一些代码(多年来第一次),使用泛型创建“重试”方法,基本上允许我使用lambda表达式重试任何代码块。以下是我的重试方法:
public static <T> Optional<T> runWithRetry(final Supplier<T> t, int retryAttempts, long retryDelayInMilliseconds) throws InterruptedException {
for(int retry = retryAttempts; retry >= 0; retry--) {
try{
return Optional.of(t.get());
}
catch(Exception e) {
if(retry == 0) {
throw e;
} else if (retryDelayInMilliseconds > 0) {
Thread.sleep(retryDelayInMilliseconds);
}
}
}
return Optional.empty();
}
我尝试这样调用这个方法:
Iterable<AvailableLicence> licences = Helpers.runWithRetry(() -> {
return licensor.findAvailableLicences(licenseOptions);
}, 3, 5000);
但是Java编译器抛出了以下错误:
error: incompatible types: no instance(s) of type variable(s) T exist so that Optional<T> conforms to Iterable<AvailableLicence>
Iterable<AvailableLicence> licences = Helpers.runWithRetry(() -> {
^
where T is a type-variable:
T extends Object declared in method <T>runWithRetry(Supplier<T>,int,long)
我想这个错误试图告诉我的是,我没有在某处指定<T>
的类型,但我不完全确定。我还结合了一些Java东西,比如Optional
和Supplier
,我不确定它们是否会导致问题,尽管我已经阅读了它们的工作原理。有人能告诉我我做错了什么吗?我觉得这是一个我在这里遗漏的简单语法问题
# 1 楼答案
我会让
runWithRetry()
的调用者不必处理选中的InterruptedException
For example like this看看我是怎么用的in my demo
因为我已经实现了
AvailableLicense.toString()
,所以我的演示输出@StuartMarks中的Optional - The Mother of all Bikesheds建议使用
Optional
查看每个人