1

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.

  • 2
    May a simple "Replace in files" or, more CLI-ish, a bunch of `sed` commands be suitable for the job? – Timor Jan 22 '23 at 21:26
  • I would do this using global text replacement in my IDE, but some command based on `find . | xargs sed -i` would work too – Bohemian Jan 22 '23 at 23:10
  • 1
    @Bohemian Thanks for the suggestion, but I want to execute the replacement in an OpenRewrite recipe as it will be part of a larger migration recipe. Sorry for the misunderstanding, I have updated the ticket. – Vincent Botteman Jan 26 '23 at 10:43
  • Hi @VincentBotteman; sorry it took a while to spot your question; we're a little more active on [Slack](https://join.slack.com/t/rewriteoss/shared_invite/zt-nj42n3ea-b~62rIHzb3Vo0E1APKCXEA), but will be monitoring StackOverflow as well. I've logged your question as [a feature request](https://github.com/openrewrite/rewrite/issues/2755), as it seems like a good (and even easy) addition. Hope that helps! – Tim Feb 02 '23 at 11:07
  • 1
    @Tim The new recipe ReplaceConstantWithAnotherConstant solves my issue. Thanks. – Vincent Botteman Apr 10 '23 at 09:44

1 Answers1

1

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!

Tim
  • 19,793
  • 8
  • 70
  • 95