1

I want to automatically replace all occurrences of

if(variable!=null && variable.equals(value)) ...

by

if(StringUtils.equals(variable, value)) ...

in a type-aware manner. That means, that variable and value should be sure to be String (not just lexicographical processing, eg. with awk/perl).

Also it should be flexible enough to apply for value as literal as well as a constant (final static) or another variable or parameter -- anything that is sure to be a String in this context. Also, there may be more boolean expressions following.

I suspect that Java Std API may help here, but the code-transformation itself is not handled by that API, just the access to the code.

3 Answers 3

3

IntelliJ IDEA's Structural Search and Replace feature is able to make such transformations. See the Web help for more information.

2

I have used JAPA known as Java parser. This is best code change tool i used. From reading a single line in if loop till saving it back to same source it has everything. Worth trying.

3
  • Good hint, I tried it. But I have the feeling it is not far with the "type-awareness" of that tool. I am stuck at how to find out if the sides of the binary expression is really a String, i.e. @Override public Node visit(BinaryExpr n, A arg) { Expression left = (Expression) n.getLeft(); Expression right = (Expression) n.getRight(); if(n.getOperator() == BinaryExpr.and) { if(left ...) ... /* how to get to the type??? */ return n; } else { /* default behaviour */ ... } I don't think javaparser is suited for that, or am I missing anything?
    – towi
    Mar 4, 2015 at 10:58
  • you can identify some pattern use Brute -force way to replace. :)
    – virendrao
    Mar 4, 2015 at 11:00
  • I don't understand, what do you mean "brute-force"? You mean the perl-ish approach inside javaparser? No, I stick with perl alone in that case.
    – towi
    Mar 4, 2015 at 11:03
1

If you are using netbeans you can use a custom refactoring:

Menu Refactor/Inspect and Transform/Browse/New/Edit Script:

<!description="Convert to StringUtils.equals">

$var!=null && $var.equals($val) :: $var instanceof java.lang.String
=> StringUtils.equals($var, $val)
;;
1
  • 1
    Nice. If you put => org.apache.commons.lang.StringUtils. in you also get the import.
    – towi
    Apr 8, 2015 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.