List of usage examples for org.eclipse.jdt.core.dom InfixExpression getStartPosition
public final int getStartPosition()
From source file:net.sf.eclipsecs.ui.quickfixes.coding.StringLiteralEqualityQuickfix.java
License:Open Source License
/** * {@inheritDoc}/*from w w w .j a v a 2 s . c o m*/ */ protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartPosition) { return new ASTVisitor() { public boolean visit(InfixExpression node) { if (containsPosition(lineInfo, node.getStartPosition())) { StringLiteral literal = null; Expression otherOperand = null; if (node.getLeftOperand() instanceof StringLiteral) { literal = (StringLiteral) node.getLeftOperand(); otherOperand = node.getRightOperand(); } else if (node.getRightOperand() instanceof StringLiteral) { literal = (StringLiteral) node.getRightOperand(); otherOperand = node.getLeftOperand(); } else { return true; } Expression replacementNode = null; MethodInvocation equalsInvocation = node.getAST().newMethodInvocation(); equalsInvocation.setName(node.getAST().newSimpleName("equals")); //$NON-NLS-1$ equalsInvocation.setExpression((Expression) ASTNode.copySubtree(node.getAST(), literal)); equalsInvocation.arguments().add(ASTNode.copySubtree(node.getAST(), otherOperand)); // if the string was compared with != create a not // expression if (node.getOperator().equals(InfixExpression.Operator.NOT_EQUALS)) { PrefixExpression prefixExpression = node.getAST().newPrefixExpression(); prefixExpression.setOperator(PrefixExpression.Operator.NOT); prefixExpression.setOperand(equalsInvocation); replacementNode = prefixExpression; } else { replacementNode = equalsInvocation; } replaceNode(node, replacementNode); } return true; } /** * Replaces the given node with the replacement node (using * reflection since I am not aware of a proper API to do this). * * @param node * the node to replace * @param replacementNode * the replacement */ private void replaceNode(ASTNode node, ASTNode replacementNode) { try { if (node.getLocationInParent().isChildProperty()) { String property = node.getLocationInParent().getId(); String setterMethodName = "set" + StringUtils.capitalize(property); Class testClass = node.getClass(); while (testClass != null) { try { Method setterMethod = node.getParent().getClass().getMethod(setterMethodName, testClass); setterMethod.invoke(node.getParent(), replacementNode); break; } catch (NoSuchMethodException e) { testClass = testClass.getSuperclass(); } } } else if (node.getLocationInParent().isChildListProperty()) { Method listMethod = node.getParent().getClass() .getMethod(node.getLocationInParent().getId(), (Class<?>[]) null); List list = (List) listMethod.invoke(node.getParent(), (Object[]) null); list.set(list.indexOf(node), replacementNode); } } catch (InvocationTargetException e) { CheckstyleLog.log(e); } catch (IllegalAccessException e) { CheckstyleLog.log(e); } catch (NoSuchMethodException e) { CheckstyleLog.log(e); } } }; }