可以使用java中的反射替换方法引用

Mot*_*ine 8 java reflection intellij-idea java-8 method-reference

我在intellij中有这个代码:

 return collection.stream().anyMatch(annotation -> 
                        method.isAnnotationPresent(annotation));
Run Code Online (Sandbox Code Playgroud)

并且编译器告诉我"method.isAnnotationPresent(annotation)"可以用方法引用替换,我无法弄清楚如何做,因为它有一个参数.

有谁知道怎么做?

dev*_*per 15

您可以替换您的代码以使用方法参考(请看这里),如下所示:

return collection.stream().anyMatch(method::isAnnotationPresent);
Run Code Online (Sandbox Code Playgroud)

基本上,您将isAnnotationPresent() 方法 定义提供给Lambda表达式(anyMatch接受Predicate的方法),并且流中的值将自动作为参数传递给anyMatch方法.