有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

泛型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东西,比如OptionalSupplier,我不确定它们是否会导致问题,尽管我已经阅读了它们的工作原理。有人能告诉我我做错了什么吗?我觉得这是一个我在这里遗漏的简单语法问题


共 (1) 个答案

  1. # 1 楼答案

    我会让runWithRetry()的调用者不必处理选中的InterruptedExceptionFor example like this

    public static <T> Optional<T> runWithRetry(final Supplier<T> t, int retryAttempts, long retryDelayInMilliseconds) {
    
        return handleSleep(t, retryAttempts, retryDelayInMilliseconds);
    }
        
    private static <T> Optional<T> handleSleep(final Supplier<T> t, int retryAttempts, long retryDelayInMilliseconds){ 
            
        Optional<T> retVal = Optional.empty();
            
        for(int retry = retryAttempts; retry >= 0; retry ) {
            try{
                retVal = Optional.of(t.get());
            }
            catch(Exception e) {
                if(retry == 0) {
                    throw e;
                } else if (retryDelayInMilliseconds > 0) {
                      try{
                          Thread.sleep(retryDelayInMilliseconds);
                      } catch(InterruptedException ie){ /*TODO: Handle or log warning */ }
                }
            }
        }
        return retVal;
    }
    

    看看我是怎么用的in my demo

    ...
    Optional<Iterable<AvailableLicense>> licenses = Deduper.runWithRetry( ()-> 
    
        { return licensor.findAvailableLicenses(licenseOptions); }, 3, 5000 );
        
    licenses.ifPresent(out::println);
    ...
    

    因为我已经实现了AvailableLicense.toString(),所以我的演示输出

    [AvailableLicense[ type: To Kill!]]
    

    @StuartMarks中的Optional - The Mother of all Bikesheds建议使用Optional查看每个人