rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

Expand getCoordinates of newClass to access arguments

Open timo-abele opened this issue 1 year ago • 1 comments

What problem are you trying to solve?

I would like to switch one constructor call for an other with JavaTemplate. E.g. if a class A offers two constructors A(int foo), A(int foo, double ba) I would like to be able to insert a new argument after, or replace the list of arguments altogether.

Describe the solution you'd like

API offers suitable methods through getCoordinates.

Have you considered any alternatives or workarounds?

Replacing the entire constructor call should work in theory. withArguments() works as well, but JavaTemplates seem to be the way to go.

Additional context

Currently a constructor call can be replaced entirely, but it would be nice to be able to operate it without putting "new A" into the template, which requires me to find out the class name at runtime. J.MethodInvocation already has getCoordinates().replaceArguments(), that could just be implemented in newClass as well.

Are you interested in contributing this feature to OpenRewrite?

probably won't find the time

timo-abele avatar Mar 09 '24 11:03 timo-abele

Thanks for the suggestion @timo-abele ; I imagine this to be very similar to how we handle J.MethodInvocation, which I think should make for a nice addition.

https://github.com/openrewrite/rewrite/blob/9bcac5a236978eaa1235b55defa2de896309e08f/rewrite-java/src/main/java/org/openrewrite/java/tree/CoordinateBuilder.java#L232-L247

Which would then need to be returned instead of CoordinateBuilder.Statement in

https://github.com/openrewrite/rewrite/blob/516c70b89ebbb43803d2dd6e0bc2cf31307a80d3/rewrite-java/src/main/java/org/openrewrite/java/tree/J.java#L4454-L4456

timtebeek avatar Mar 12 '24 16:03 timtebeek