开发者

How replace String catenation to StringBuilder append?

开发者 https://www.devze.com 2023-02-08 05:19 出处:网络
How can recursively replace all catenations in toString method to StringBuilder for Java? Is there such a plugin in eclipse?

How can recursively replace all catenations in toString method to StringBuilder for Java? Is there such a plugin in eclipse? For example: Replace it:

    return "AccountAddresses ["
            + ", corporateAddresses=" + CommonHelper.isNotNull(corporateAddresses)
            + ", corporateDeliveryMinimum=" + corporateDeliveryMinimum
            + ", depot=" +  CommonHelper.isNotNull(depot)
            + ", depotDeliveryMinimum=" + depotDeliveryMinimum
            + ", preSelectedId=" + preSelectedId
            + ", residentialAddresses=" +  CommonHelper.isNotNull(residentialAddresses)
            + ", residentialDeliveryMinimum=" + residentialDeliveryMinimum
            + "]";

at this:

    return new StringBuilder("AccountAddresses [")
            .append(", corporateAddresse开发者_开发技巧s=").append(CommonHelper.isNotNull(corporateAddresses))
            .append(", corporateDeliveryMinimum=").append(corporateDeliveryMinimum)
            .append(", depot=").append(CommonHelper.isNotNull(depot))
            .append(", depotDeliveryMinimum=").append(depotDeliveryMinimum)
            .append(", preSelectedId=").append(preSelectedId)
            .append(", residentialAddresses=").append(CommonHelper.isNotNull(residentialAddresses))
            .append(", residentialDeliveryMinimum=").append(residentialDeliveryMinimum)
            .append("]").toString();


It's a builtin command of Eclipse.

  • Click on one of the quotation marks (") in your String concatenation.
  • Bring the Quick Fix menu (Hit Ctrl + 1 on the keyboard).
  • Select Use 'StringBuilder' for String concatenation.

Magic! Your

    return "foo" + "bar";

changed to

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("foo");
    stringBuilder.append("bar");
    return stringBuilder.toString();


I haven't heard of an Eclipse plugin for this - so feel free to ignore this off topic answer - but IntelliJ has an "intention" that will do it for you (at least in 10.0 it does). There is a community edition available if you want to give it a shot.


Do a regex search and replace :

", ([a-zA-z0-9]+)=" \+ CommonHelper\.isNotNull\(([a-zA-z0-9]+)\)  // Find this

append(", $1=").append(CommonHelper.isNotNull($2))    // and replace with this

It is not complete, but you get the idea.


Why dont you override the toString method in your class , and implement the stringbuilder append.


I don't think any plugin would do that for you... this would be useless anyways : the Java compiler will do it better than anyone can (and if "StringBuilder" is ever replaced by something better, the Java compiler will be able to use this "something better" if you do not explicitely use a StringBuilder).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号