PsiElementVisitor (@NotNull ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) { PsiElement nameElement = call.getMethodExpression().getReferenceNameElement(); if (nameElement == null) return; if (!OptionalUtil.OPTIONAL_GET.test(call)) return; PsiExpression qualifier = PsiUtil.skipParenthesizedExprDown(call.getMethodExpression().getQualifierExpression()); if (qualifier == null) return; PsiClass optionalClass = PsiUtil.resolveClassInClassTypeOnly(qualifier.getType()); if (optionalClass == null) return; JavaExpressionAnchor anchor = new JavaExpressionAnchor(qualifier); if (isOptionalProblem(qualifier, anchor) && !isPresentCallWithSameQualifierExists(qualifier)) { holder.registerProblem(nameElement, JavaBundle.message("inspection.optional.get.without.is.present.message", optionalClass.getName()), LocalQuickFix.notNullElements(tryCreateFix(call))); } } private static boolean isOptionalProblem(@NotNull PsiExpression context, @NotNull JavaDfaAnchor anchor) { CommonDataflow.DataflowResult result = CommonDataflow.getDataflowResult(context); if (result == null || !result.anchorWasAnalyzed(anchor)) return false; DfType dfType = SpecialField.OPTIONAL_VALUE.getFromQualifier(result.getDfType(anchor)); if (dfType != DfType.TOP && !(dfType instanceof DfReferenceType)) return false; DfaNullability nullability = DfaNullability.fromDfType(dfType); return nullability == DfaNullability.UNKNOWN || nullability == DfaNullability.NULLABLE; } @Override public void visitMethodReferenceExpression(@NotNull PsiMethodReferenceExpression methodRef) { if (!OptionalUtil.OPTIONAL_GET.methodReferenceMatches(methodRef)) return; if (isOptionalProblem(methodRef, new JavaMethodReferenceArgumentAnchor(methodRef))) { holder.registerProblem(methodRef, JavaBundle.message("inspection.optional.get.without.is.present.method.reference.message")); } } public boolean isPresentCallWithSameQualifierExists(PsiExpression qualifier) { // Conservatively skip the results of method calls if there's an isPresent() call with the same qualifier in the method if (qualifier instanceof PsiMethodCallExpression) { PsiElement context = PsiTreeUtil.getParentOfType(qualifier, PsiMember.class, PsiLambdaExpression.class); if (context != null) { return !PsiTreeUtil.processElements(context, e -> { if (e == qualifier || !(e instanceof PsiMethodCallExpression call)) return true; String name = call.getMethodExpression().getReferenceName(); if ((!"isPresent".equals(name) && !"isEmpty".equals(name)) || !call.getArgumentList().isEmpty()) return true; PsiExpression isPresentQualifier = call.getMethodExpression().getQualifierExpression(); return isPresentQualifier == null || !PsiEquivalenceUtil.areElementsEquivalent(qualifier, isPresentQualifier); }); } } return false; } }; }