Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automate Java code refactoring using a script with instructions?

How to refactor this class programmatically via Java code/Groovy plugin? Let's say, I need to:

  • Rename foo.method2 to foo.method3
  • Rename myMethod to yourMethod
  • Change the imported package org.you.core.util.AnotherClassFromExternalPackage
import com.me.core.util.AnotherClassFromExternalPackage;
import com.me.core.util.Foo;

public class MyClass implements AnotherClassFromExternalPackage {

    private final Foo foo;

    public MyClass() {
        this.foo = new Foo();
    }

    @Override
    public long myMethod() {
        return foo.method2();
    }
}

How to create a script that will parse the code, apply syntactical transformations and save it using given instructions?

The code above is just an example. The bigger problem is that I have a lot of projects that are using the same external library. And sometimes they release a new version with breaking changes that is breaking the current code after the dependency bump. And I must update the dependency to the latest version every 2 weeks for 10+ projects. I need to write a script that will fix these breaking changes automatically. Ideally, apply code transformations one by one.

like image 489
Garruk The Wildspeaker Avatar asked May 25 '26 17:05

Garruk The Wildspeaker


1 Answers

Sounds like a job for OpenRewrite. Standard recipes, e.g., for renaming a package are available. You can also write your own recipes, which make use of a visitor pattern over a tree-based representation of your source code (which will preserve, e.g., indentation).

You can use Maven or Gradle to execute the rewrite.

For instance the change package configuration from the getting started page looks like this:

type: specs.openrewrite.org/v1beta/recipe
name: com.yourorg.VetToVeterinary
recipeList:
  - org.openrewrite.java.ChangePackage:
    oldPackageName: org.springframework.samples.petclinic.vet
    newPackageName: org.springframework.samples.petclinic.veterinary
like image 81
cw' Avatar answered May 27 '26 05:05

cw'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!