Question

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);
Was it helpful?

Solution

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

Arrays.asList(line).forEach(e-> assertNotNull(e));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top