Question

I am using sun-codemodel to generate code. I have problem with generics. I know that to generate something like

LinkedList<String>,

I need to use

JType jtype = jCodeModel.ref("LinkedList").narrow(jCodeModel.ref("String"));

However, how do I create something more general, for more than one generic type?

HashMap<String,Integer>

I would like to do it in the loop so that it supports any number of arguments in custom classes, but for the code like:

for(String name: names()){
  returnTypeClass = jCodeModel.ref(name).narrow(jCodeModel.ref(name));
}

the output is something like this:

JNarrowedClass(JCodeModel$JReferencedClass(HashMap)<Integer>)<String>
Was it helpful?

Solution

I'm unfamiliar with CodeModel, but looking at the API documentation it seems there's a varargs overload: narrow(JClass...). Presumably this is used for resolving multiple type parameters. So in the case of HashMap<String, Integer>, you would do:

JType jtype = jCodeModel.ref("HashMap").narrow(
        jCodeModel.ref("String"),
        jCodeModel.ref("Integer")
);

And generalizing this to your loop:

Collection<JClass> typeArgClasses = new ArrayList<>();
for (String name : names()) {
    typeArgClasses.add(jCodeModel.ref(name));
}
JType jtype = jCodeModel
        .ref(typeName)
        .narrow(typeArgClasses.toArray(new JClass[typeArgClasses.size()]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top