From 3198fbf508ae4ef8b59ef193c2c9ef7852b55055 Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Fri, 19 Feb 2016 15:13:41 +0100 Subject: [PATCH] IDEA-151898 (Optional.get without isPresent) --- .../OptionalGetWithoutIsPresentInspection.java | 10 ++++++---- ...OptionalGetWithoutIsPresentInspectionTest.java | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspection.java index c3450ac9c44f..84136584ac14 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspection.java @@ -62,16 +62,18 @@ public class OptionalGetWithoutIsPresentInspection extends BaseInspection { return; } final PsiExpression qualifier = ParenthesesUtils.stripParentheses(methodExpression.getQualifierExpression()); - if (!(qualifier instanceof PsiReferenceExpression)) { + if (qualifier == null) { return; } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifier; final PsiType type = qualifier.getType(); if (!TypeUtils.isOptional(type)) { return; } - if (isSurroundedByIsPresentGuard(referenceExpression)) { - return; + if (qualifier instanceof PsiReferenceExpression) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifier; + if (isSurroundedByIsPresentGuard(referenceExpression)) { + return; + } } registerMethodCallError(expression, type); } diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspectionTest.java index fe2e7b57082d..967289810d73 100644 --- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspectionTest.java +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/OptionalGetWithoutIsPresentInspectionTest.java @@ -43,6 +43,18 @@ public class OptionalGetWithoutIsPresentInspectionTest extends LightInspectionTe "}"); } + public void testOptionalWithoutVariable() { + doTest("import java.util.Optional;" + + "class X {" + + " {" + + " System.out.println(getName()./*'Optional.get()' without 'isPresent()' check*/get/**/());" + + " }" + + " Optional getName() {" + + " return Optional.empty();" + + " }" + + "}"); + } + @Nullable @Override protected InspectionProfileEntry getInspection() { @@ -60,6 +72,9 @@ public class OptionalGetWithoutIsPresentInspectionTest extends LightInspectionTe " public boolean isPresent() {" + " return true;" + " }" + + " public static Optional empty() {" + + " return new Optional<>();" + + " }" + "}", "package java.util;" +