Search code examples
javacode-translation

How to replace all String.equals by StringUtils.equals


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.


Solution

  • 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)
    ;;