Generating a constructor call with type arguments

I want to use TreeMakerto generate a constructor call for a type with type arguments in my netbeans code generator module. In addition, I want to import types, and not use full names (see QualIdent).

I am using a method NewClassfor this purpose.

Example:

Given the input java.util.ArrayListand java.lang.Integer, the generated code should look something like this:

import java.util.ArrayList;

...

new ArrayList<Integer>();

If the input java.util.ArrayListand java.util.List<java.lang.Integer>, the generated code should look something like this:

import java.util.ArrayList;
import java.util.List;

...

new ArrayList<List<Integer>>();

(A list of type arguments is stored as List<? extends TypeMirror>)

How can I generate the desired result?

What I have tried so far:

( maker- this is an instance TreeMaker)

  • Convert type name to 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);
    

    / Java-, , .. new java.util.ArrayList<java.util.List<java.lang.Integer>>()

  • typeArguments 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);
    

    import ArrayList, , new, .. new <Integer>ArrayList(), .

  • ParameterizedTypeTree , , TreeMaker type ExpressionTree, ParameterizedTypeTree.

+4

Source: https://habr.com/ru/post/1628343/


All Articles