How to replace static imports of class constants in OpenRewrite?

299 Views Asked by At

I want to replace static imports of class constants with other class constants.

Example:

Original code

import javax.ws.rs.*;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

class ControllerClass {
    @Produces(APPLICATION_JSON)
    public String getHelloWorldJSON(String name) {
        return "{}";
    }
}

Expected code

import javax.ws.rs.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

class ControllerClass {
    @Produces(APPLICATION_JSON_VALUE)
    public String getHelloWorldJSON(String name) {
        return "{}";
    }
}

So I don't want to only replace the class type (javax.ws.rs.core.MediaType -> org.springframework.http.MediaType ) but also the name of the class constant (APPLICATION_JSON -> APPLICATION_JSON_VALUE)

I tried using the OpenRewrite ChangeType recipe but that only changed the class type, not the class constant. I want to execute this replacement in an OpenRewrite recipe as it will be part of a larger migration.

1

There are 1 best solutions below

0
On

This has since been implemented, and documented here. It can be used with an example rewrite.yml file:

type: specs.openrewrite.org/v1beta/recipe
name: com.yourorg.ReplaceConstantWithAnotherConstantExample
displayName: Replace constant with another constant example
recipeList:
  - org.openrewrite.java.ReplaceConstantWithAnotherConstant:
      existingFullyQualifiedConstantName: javax.ws.rs.core.MediaType.APPLICATION_JSON
      fullyQualifiedConstantName: org.springframework.http.MediaType.APPLICATION_JSON_VALUE

Thanks for the suggestion!