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?
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With