Java 需要可运行对象,但传入了一个方法

Java runnable object expected but passed in a method

这行我不太明白:

article.getMoneyBackGuarantee().on(today).claim(this::offerMoneyBack);

在下面的代码中:

public class Demo {
private void offerMoneyBack() {
    System.out.println("Offer money back.");
}

private void offerRepair() {
    System.out.println("Offer repair.");
}

public void claimWarranty(Article article) {
    LocalDate today = LocalDate.now();

    article.getMoneyBackGuarantee().on(today).claim(this::offerMoneyBack);
    article.getExpressWarranty().on(today).claim(this::offerRepair);

    System.out.println("-----------------");
}

public void run() {
    LocalDate sellingDate = LocalDate.now().minus(40, ChronoUnit.DAYS);
    Warranty moneyBack1 = new TimeLimitedWarranty(sellingDate, Duration.ofDays(60));
    Warranty warranty1 = new TimeLimitedWarranty(sellingDate, Duration.ofDays(365));

    Article item1 = new Article(moneyBack1, warranty1);

    this.claimWarranty(item1);
    this.claimWarranty(item1.withVisibleDamage());
    this.claimWarranty(item1.notOperational().withVisibleDamage());
    this.claimWarranty(item1.notOperational());

    Article item2 = new Article(Warranty.VOID, Warranty.lifetime(sellingDate));
    this.claimWarranty(item2.withVisibleDamage().notOperational());
}


public interface Warranty {
    Warranty on(LocalDate date);
    default void claim(Runnable action) { action.run(); }

    Warranty VOID = new VoidWarranty();

    static Warranty lifetime(LocalDate issuedOn) {
        return new LifetimeWarranty(issuedOn);
    }
}

getMoneyBackGuarantee() 和 on() 方法都是 return 一个 Warranty 对象,所有 Warranty 对象的实现都有相同的 claim() 方法。我的问题是,这 运行 怎么办? claim 方法需要一个 运行nable 对象,但我们向它传递了一个方法引用? (例如 this::offerMoneyBack)

Runnable 是函数式接口,因此可以用 lambda 表达式或方法引用代替。
这就是你在这里得到的 - claim(Runnable action) 可以获得对满足 Runnable#run 签名的方法的任何 lambda 或方法引用 - 获得零参数和 return void,无论此方法是否被调用 运行 或者如果 class 实现接口 - 如果签名合适 - 它可以作为功能接口工作。