in comparing_string_references_inspection/src/main/java/org/intellij/sdk/codeInspection/ComparingStringReferencesInspection.java [34:80]
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
/**
* Evaluate binary PSI expressions to see if they contain relational operators '==' and '!=',
* AND they are of String type.
* The evaluation ignores expressions comparing an object to null.
* IF these criteria are met, register the problem in the ProblemsHolder.
*
* @param expression The binary expression to be evaluated.
*/
@Override
public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) {
super.visitBinaryExpression(expression);
IElementType opSign = expression.getOperationTokenType();
if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) {
// The binary expression is the correct type for this inspection
PsiExpression lOperand = expression.getLOperand();
PsiExpression rOperand = expression.getROperand();
if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) {
return;
}
// Nothing is compared to null, now check the types being compared
if (isStringType(lOperand) || isStringType(rOperand)) {
// Identified an expression with potential problems, register problem with the quick fix object
holder.registerProblem(expression,
InspectionBundle.message("inspection.comparing.string.references.problem.descriptor"),
myQuickFix);
}
}
}
private boolean isStringType(PsiExpression operand) {
PsiClass psiClass = PsiTypesUtil.getPsiClass(operand.getType());
if (psiClass == null) {
return false;
}
return "java.lang.String".equals(psiClass.getQualifiedName());
}
private static boolean isNullLiteral(PsiExpression expression) {
return expression instanceof PsiLiteralExpression &&
((PsiLiteralExpression) expression).getValue() == null;
}
};
}