I want to use TreeMaker
to generate a constructor call for a type with type arguments in my netbeans code generator plugin. Additionally I want to import types rather than using the fully qualified names (see QualIdent
).
I'm using the NewClass
method for this purpose.
Example:
Given input java.util.ArrayList
and java.lang.Integer
the generated code should look similar to this:
import java.util.ArrayList;
...
new ArrayList<Integer>();
If the input is java.util.ArrayList
and java.util.List<java.lang.Integer>
the generated code should look similar to this:
import java.util.ArrayList;
import java.util.List;
...
new ArrayList<List<Integer>>();
(The type argument list is stored as List<? extends TypeMirror>
)
How can I generate the desired output?
What I've tried so far:
(maker
is the TreeMaker
instance)
Convert type name to a string:
String className = "java.util.ArrayList<java.util.List<java.lang.Integer>>"; // actually computed in real code maker.NewClass(null, Collections.<ExpressionTree>emptyList(), maker.QualIdent(className), Collections.<ExpressionTree>emptyList(), null);
This yields syntactically/semantically correct java code, but uses the fully qualified class names, i.e.
new java.util.ArrayList<java.util.List<java.lang.Integer>>()
Pass as
typeArguments
toNewClass
:List<ExpressionTree> typeArguments = Collections.singletonList(maker.QualIdent("java.lang.Integer")); // actually computed in real code maker.NewClass(null, typeArguments, maker.QualIdent("java.util.ArrayList"), Collections.<ExpressionTree>emptyList(), null);
This does import
ArrayList
, but the type arguments are added directly after thenew
keyword, i.e.new <Integer>ArrayList()
is generated, which is wrong.Use a
ParameterizedTypeTree
as identifier for the type, which doesn't work, sinceTreeMaker
expects a parameter of typeExpressionTree
, but that's not a supertype ofParameterizedTypeTree
.