(Java 8)java.util.function.Supplier [英] (Java 8) java.util.function.Supplier

查看:100
本文介绍了(Java 8)java.util.function.Supplier的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我尝试使用供应商调用info方法. (info方法已重载:一个正在使用字符串,另一个正在使用供应商.)编译器抱怨方法info(String)不适用于参数Supplier<Double>".我的期望是通过发送Supplier对象来调用info方法以获取Supplier.我可以得到一些帮助来了解此错误吗?

In the following code, I tried to call the info method taking a Supplier. (The info method is overloaded: one is taking a String and the other is taking a Supplier.) The compiler complains that "The method info(String) is not applicable for the argument Supplier<Double>". My expectation is to call the info method taking a Supplier by sending a Supplier object. Can I get some help to understand this error?

Supplier<Double> randomSupplier = new Supplier<Double>()
{   public Double get()
    {   return Math.random(); }    
};

logger.info(randomSupplier); <----

推荐答案

假设您的loggerjava.util.logging.Logger. .

根据用于Logger.info 的Javadoc,它需要一个Supplier<String>,而您给它一个Supplier<Double>.

According to the Javadoc for Logger.info, it expects a Supplier<String>, and you're giving it a Supplier<Double>.

要解决此问题,您需要给它一个Supplier<String>.您可以这样写一个:

To fix this, you need to give it a Supplier<String>. You can write one either like this:

final Supplier<String> randomSupplier =
    new Supplier<String>() {
        public String get() {
            return Double.toString(Math.random());
        }
    };

或类似这样:

final Supplier<String> randomSupplier =
    () -> Double.toString(Math.random());

您甚至可以写:

logger.info(() -> Double.toString(Math.random()));

并且Java会神奇地推断出您的lambda应该是Supplier<String>(因为info的其他重载没有采用功能性的接口类型).

and Java will magically infer that your lambda is meant to be a Supplier<String> (because the other overload of info doesn't take a functional interface type).

这篇关于(Java 8)java.util.function.Supplier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆