Can be replaced by a method reference using reflection in java

I have this code in intellij:

return collection.stream().anyMatch(annotation -> method.isAnnotationPresent(annotation)); 

And the compiler tells me that "method.isAnnotationPresent (annotation)" can be replaced with a reference to a method, and I cannot figure out how to do this because it has an argument.

Does anyone know how to do this?

+7
java reflection intellij-idea java-8 method-reference
source share
1 answer

You can replace your code with a method reference (see here ), as shown below:

 return collection.stream().anyMatch(method::isAnnotationPresent); 

Basically, you provide the isAnnotationPresent() definition method for the Lambda expression (the anyMatch method that accepts for Predicate ), and the value from the stream will be automatically passed as an argument to anyMatch method.

+13
source share

All Articles