Adding IDE assistance for extension method creating map constructor

Answered

Hi,

I have a Java codebase that I test with Groovy. We have an entrenched pattern of “config classes”, which are immutable value classes with defaults. They look like this:

 

public final class SomeConfig {

public final String someParam;
public final String someOtherParam;

public SomeConfig(String someParam, String someOtherParam) {
this.someParam = someParam == null ? "default" : someParam;
this.someOtherParam = someOtherParam == null ? "default" : someOtherParam;
}

}

 

These can end up with several fields and constructor params. It's common to want to construct one of these at test time and just augment one default. Ideally, this would work in Groovy…

new SomeConfig(someParam: "overridden")

To construct this while just overriding that one param. I have a Groovy extension method that does this via a factory method…

final class ConfigTypeExtension {

static <T> T createConfig(Class<T> clazz, Map<String, ?> map = [:]) {
def constructor = clazz.constructors.first()
def params = []
constructor.parameters.each {
params << map[it.name]
}
constructor.newInstance(params.toArray()) as T
}

}

This allows:

SomeConfig.createConfig(someParam: "overridden")

My question is: Is there anyway I can make IDEA understand this relationship? Ideally I would be able to autocomplete the map entry names for the createConfig() method, and ideally ideally have the map keys be navigable through to the constructor.

I took a brief look at GDSL and wasn't sure if it could achieve this or whether it was now defunct.

 

 

 

 

4 comments
Comment actions Permalink
Official comment

It’s not possible with gdsl, and you need to create a plugin with an implementation of GroovyNamedArgumentProvider extension. Please check out GroovyConstructorNamedArgumentProvider as a reference.

Also you probably want to look into Kotlin data classes, as they have this behaviour out of the box, so no plugin is needed.

Comment actions Permalink

Thank you Daniil.

0
Comment actions Permalink

Looks interesting

0
Comment actions Permalink

 I work on my java project now in college. Plus I need to write three assignments. From time to time I got help from others who do my java assignment for me because I have lack of time and need to improve grammar

0

Please sign in to leave a comment.