Search code examples
javaeclipseeclipse-plugineclipse-jdtparameterized-types

Copy type arguments of org.eclipse.jdt.core.dom.ParameterizedType


I am trying to copy the type arguments from an existing org.eclipse.jdt.core.dom.ParameterizedType to a newly created one. The problem is that you cannot just add the type arguments from one type to another one because the arguments already have a parent.

This is my code:

AST ast = ... // some ast 
Type oldType = ... // existing type from ast
String name = ... // The name of the new type
Type newType = ast.newSimpleType(ast.newName(name));
if (oldType.isParameterizedType()) {
    ParameterizedType newParameterizedType = ast.newParameterizedType(newType);
    for (Object type : ((ParameterizedType) oldType).typeArguments()) {
         newParameterizedType.typeArguments().add(type); // throws illegal argument exception at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:2087)
    }
    newType = newParameterizedType; // use parameterized type
}

How can I copy the type arguments of the old type without making the mistake which I currently make in the loop?


Solution

  • As Brian suggested, using delete() solved that problem. This was originally proposed in this question. The type arguments from an existing ParameterizedType first have to be removed from the AST before adding them to a newly created ParameterizedType. This pertains to every ASTNode.

    This is my solution using delete():

    AST ast = ... // some ast 
    Type oldType = ... // existing type from ast
    String name = ... // The name of the new type
    Type newType = ast.newSimpleType(ast.newName(name));
    if (oldType.isParameterizedType()) {
        ParameterizedType newParameterizedType = ast.newParameterizedType(newType);
        for (Object type : ((ParameterizedType) oldType).typeArguments()) {
             type.remove(); // <-- THIS LINE SOLVES THE PROBLEM
             newParameterizedType.typeArguments().add(type);
        }
        newType = newParameterizedType; // use parameterized type
    }