Pregunta

Is there a way to call Iterable#forEach with a statically imported method as argument? I got this to work by typing the fully qualified name for the function, without importing it:

Arrays.asList(line).forEach(org.junit.Assert::assertNotNull);

Another variant being:

import org.junit.Assert;
...
Arrays.asList(line).forEach(Assert::assertNotNull);

The reason for this, is I want to assertNotNull every element in line in a unit test, but I don't like using fully qualified names for that stuff. It would have been nice to just use:

import static org.junit.Assert.assertNotNull;
...
Arrays.asList(line).forEach(assertNotNull);
¿Fue útil?

Solución

No. You'll have to revert to classical lambda notation to do that:

Arrays.asList(line).forEach(e-> assertNotNull(e));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top