[英]LOGGER::info is not consumed as s -> LOGGER.info(s)
I have defined a logger instance as follows: 我定义了一个记录器实例,如下所示:
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
I have an array of strings that I want to log, so I used the following: 我有一个要记录的字符串数组,因此使用了以下内容:
Arrays.stream(new String[]{"ABC", "DEF", "XYZ"}).forEach(LOGGER::info);
However, nothing is printed into the log. 但是,没有任何内容打印到日志中。 But, if I change the reference method to an equivalent lambda form, it prints into the log:
但是,如果我将引用方法更改为等效的lambda形式,它将打印到日志中:
Arrays.stream(new String[]{"ABC", "DEF", "XYZ"}).forEach(s -> LOGGER.info(s));
What am I missing here? 我在这里想念什么?
I tried the following approaches as well and they all behave the same: 我也尝试了以下方法,它们的行为都相同:
Stream.of("ABC", "DEF", "XYZ").forEach(LOGGER::info);
List.of("ABC", "DEF", "XYZ").forEach(LOGGER::info);
Even Intellij IDE highlights s -> LOGGER.info(s)
with yellow and suggests changing it to LOGGER::info
. 甚至Intellij IDE也用黄色突出显示
s -> LOGGER.info(s)
,并建议将其更改为LOGGER::info
。
I tried to define a custom class: 我试图定义一个自定义类:
static class Consumer
{
void consume(String s)
{
LOGGER.info(s);
}
}
and use it in place of LOGGER::info
: 并用它代替
LOGGER::info
:
Consumer consumer = new Consumer();
Arrays.stream(new String[]{"ABC", "DEF", "XYZ"}).forEach(consumer::consume);
It prints into the log! 它打印到日志中!
The Logger
class has two overloaded methods: Logger
类具有两个重载方法:
void info(String msg)
and 和
void info(Supplier<String> msgSupplier)
but only the first is assignable to void forEach(Consumer<? super T> action)
, I believe. 但我相信只有第一个可分配给
void forEach(Consumer<? super T> action)
。
Consider that code: 考虑以下代码:
Arrays.stream(new String[]{"ABC"}).forEach(LOGGER::info);
Arrays.stream(new String[]{"ABC"}).forEach(s -> LOGGER.info(s));
The difference is in the first case source of message is: 在第一种情况下,消息源的区别是:
java.util.Spliterators$ArraySpliterator
in the second: 在第二:
Main
Probably your logger has some filter that does not let logging events from java.util.Spliterators$ArraySpliterator
class. 记录器可能有一些过滤器,该过滤器不允许记录来自
java.util.Spliterators$ArraySpliterator
类的事件。
Try to check result of LOGGER.getFilter()
尝试检查
LOGGER.getFilter()
结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.