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:
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
.
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
:
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:
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.
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.
Try to check result of LOGGER.getFilter()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.