Writing a Java refactoring recipe
Adding a method to a class that returns a String
To help you get started with writing recipes, this guide will walk you through all the steps needed to create a basic refactoring recipe. This
SayHelloRecipe
will add a hello()
method to a user specified class if that class does not already have one.For example, it would take a class like this:
package com.yourorg;
class FooBar {
}
And refactor it into a class like this:
package com.yourorg;
class FooBar {
public String hello() {
return "Hello from com.yourorg.FooBar!";
}
}
This guide assumes you've already set up your Recipe Development Environment and that you are familiar with writing Java code.
Let's begin by creating a Java class that extends
org.openrewrite.Recipe
. At a minimum, this recipe should have:- An
Option
that is the fully qualified name of the class you want to add thehello()
method to. - A serializable constructor that takes in the fully qualified class name.
- A
getDisplayName()
method that returns the display name for this recipe. - A
getDescription()
method that returns the description for this recipe.
Here is what the class should look like with just these things defined:
package com.yourorg;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.NonNull;