PsiElementVisitor (@NotNull ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitLocalVariable(@NotNull PsiLocalVariable variable) { if (!(variable instanceof PsiResourceVariable)) { processVariable(variable, PsiUtil.getVariableCodeBlock(variable, null)); } } @Override public void visitField(@NotNull PsiField field) { if (field.hasModifierProperty(PsiModifier.PRIVATE)) { processVariable(field, PsiUtil.getTopLevelClass(field)); } } @Override public void visitNewExpression(@NotNull PsiNewExpression expression) { PsiMethodCallExpression nextCall = ExpressionUtils.getCallForQualifier(expression); PsiJavaCodeReferenceElement anchor = expression.getClassOrAnonymousClassReference(); if (anchor != null && nextCall != null && isNewExpression(expression) && isWriteOnlyCall(nextCall, true)) { holder.registerProblem(anchor, InspectionGadgetsBundle.message("write.only.object.display.name")); } } @Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) { PsiMethodCallExpression nextCall = ExpressionUtils.getCallForQualifier(call); PsiElement anchor = call.getMethodExpression().getReferenceNameElement(); if (anchor != null && nextCall != null && isNewExpression(call) && isWriteOnlyCall(nextCall, false)) { holder.registerProblem(anchor, InspectionGadgetsBundle.message("write.only.object.display.name")); } } private void processVariable(PsiVariable variable, PsiElement block) { if (block == null) return; PsiExpression initializer = PsiUtil.skipParenthesizedExprDown(variable.getInitializer()); PsiIdentifier identifier = variable.getNameIdentifier(); if (identifier != null && isNewExpression(initializer)) { boolean exactType = PsiUtil.skipParenthesizedExprDown(initializer) instanceof PsiNewExpression; PsiType type = variable.getType(); if (!(type instanceof PsiClassType)) return; if (InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_COLLECTION) || InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_MAP) || InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER)) { // will be processed by other inspections return; } List<PsiReferenceExpression> references = VariableAccessUtils.getVariableReferences(variable, block); if (references.isEmpty()) return; for (PsiReferenceExpression ref : references) { if (!isWriteWithoutRead(ref, exactType)) { return; } } holder.registerProblem(identifier, InspectionGadgetsBundle.message("write.only.object.display.name")); } } }; }