Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can be replaced with 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 method reference and I can't figure out how to do it because it has an argument.

Does anyone know how to make that?

like image 642
Motomine Avatar asked Apr 09 '17 22:04

Motomine


People also ask

Can we replace lambda expression with method reference?

out::println); The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

How do you call a method dynamically in Java?

Java Reflection API provides us information about a Class to which the Object belongs to including the methods in this class. Using these Reflection API we would be able to get invoking pointer for a method in a class with its name.

What is static method reference in Java?

A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName , where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount .


1 Answers

You can replace your code to use the method reference (look here) as shown below:

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

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

like image 54
developer Avatar answered Oct 21 '22 05:10

developer