rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

Recipe to replace autoboxing with explicit `valueOf`

Open JasperTeng opened this issue 1 year ago • 1 comments

What problem are you trying to solve?

When using ParameterizedLogging, the output is not compatible in my IDE, since restriction is placed on autoboxing usage. I wish I can apply another recipe that performs automatic wrapping of those primitives. Note1: its fine if all applicable primitives are changed, since the entire project doesn't use autoboxing in the first place. Note2: should be applicable to all primitives that can be autoboxed. i.e.: byte, short, int, long, float, double, char, boolean

What precondition(s) should be checked before applying this recipe?

Nil.

Describe the situation before applying the recipe

class A {
    void bar() {
        int i = 0;
        foo(i);
    }
    void foo(Integer bar) {
        // do something
    }
}

Describe the situation after applying the recipe

class A {
    void bar() {
        int i = 0;
        foo(Integer.valueOf(i));
    }
    void foo(Integer bar) {
        // do something
    }
}

Have you considered any alternatives or workarounds?

Unfortunately, I did not manage to fine any recipe, or rewrite tool, that supports this. I was hoping IDE (Eclipse) can separate autoboxing and autounboxing criticality, but it doesn't allow me to do so.

Any additional context

Nil.

Are you interested in contributing this recipe to OpenRewrite?

Sure, if someone more experienced tells me its possible to create such a recipe. I am afraid to dig deep into it, only to find out it is not possible with the current openrewrite concept.

JasperTeng avatar May 07 '24 05:05 JasperTeng

Hi @JasperTeng ; Thanks for the suggestion! The closest we have right now is this recipe to remove autoboxing where Boolean's are involved: https://github.com/openrewrite/rewrite-static-analysis/blob/c2fffaf2929a8eafbb050ba21cb55d1b0371d12c/src/main/java/org/openrewrite/staticanalysis/AvoidBoxedBooleanExpressions.java#L31-L41

It sounds like your suggestion would be a separate recipe where we visit any method invocation, figure out if the types are boxed versions of the argument types passed in, and if so replace the arguments with explicit boxing. Would you also want to handle cases where there's a need to go from Integer to int?

I think it should be possible to create such a recipe with the type information that we have. You can look here to get started with either a fork of this repository, or a custom recipe module for your own purposes based on the moderneinc/rewrite-recipe-starter.

timtebeek avatar May 07 '24 09:05 timtebeek