5

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)

  1. 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>>()

  2. Pass as typeArguments to NewClass:

    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 the new keyword, i.e. new <Integer>ArrayList() is generated, which is wrong.

  3. Use a ParameterizedTypeTree as identifier for the type, which doesn't work, since TreeMaker expects a parameter of type ExpressionTree, but that's not a supertype of ParameterizedTypeTree.

rostanek
  • 623
  • 4
  • 11
fabian
  • 80,457
  • 12
  • 86
  • 114

0 Answers0