Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow method references in Optional orElse #709

Merged
merged 3 commits into from
Jul 25, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,9 @@ public final class OptionalOrElseMethodInvocation extends BugChecker implements
.onExactClass("java.util.Optional")
.named("orElse");

private static final Matcher<ExpressionTree> METHOD_OR_CONSTRUCTOR = Matchers.anyOf(
MethodMatchers.anyMethod(),
MethodMatchers.constructor());

private static final Matcher<ExpressionTree> METHOD_INVOCATIONS = Matchers.anyOf(
METHOD_OR_CONSTRUCTOR,
Matchers.contains(ExpressionTree.class, METHOD_OR_CONSTRUCTOR));
MethodInvocationMatcher.INSTANCE,
Matchers.contains(ExpressionTree.class, MethodInvocationMatcher.INSTANCE));

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Expand All @@ -74,4 +70,21 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState
.build();
}

private enum MethodInvocationMatcher implements Matcher<ExpressionTree> {

INSTANCE;

@Override
public boolean matches(ExpressionTree tree, VisitorState state) {
switch (tree.getKind()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps an if statement instead of a switch?

case NEW_CLASS:
case METHOD_INVOCATION:
return true;
default:
break;
}

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,21 @@ public void testVariable() {
.doTest();
}

@Test
public void testMethodReference() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"import java.util.function.Supplier;",
"class Test {",
" String f() { return \"hello\"; }",
" private final Optional<Supplier<String>> optionalSupplier = Optional.of(() -> \"hello\");",
" private final Supplier<String> supplier = optionalSupplier.orElse(this::f);",
"}")
.doTest();
}

@Test
public void testOrElseGet() {
compilationHelper
Expand Down