Search code examples
javaeclipsegenericseclipse-jdtraw-types

Safely adding objects to a raw list that cannot be set (Java AST)


I am working with the Java AST (JDT) and have to add org.eclipse.jdt.core.dom.Type instances to a raw list (pre-Java 5 code), which only contains elements of type Type (The API guarantees it). I access the list with TypeDeclaration.superInterfaceTypes() Because of how the class TypeDeclaration is written (there is no setter for the super interface types), I have to add the elements directly and cannot simply create a List<Type> instance, copy the elements, add my new element and then set the new list. Therefore I end up with a compiler warning.

This is my current code:

@SuppressWarnings("unchecked")
private void changeSuperInterface(TypeDeclaration declaration) {
    // some code...
    Type newInterface = ast.newSimpleType(ast.newName(name));
    declaration.superInterfaceTypes().remove(oldInterface);
    declaration.superInterfaceTypes().add(newInterface); // Type safety warning here.
}

Can I solve this with a solution that is more elegant than just suppressing the warning?


Solution

  • In your project properties or workspace preferences Java (>) Compiler > Errors/Warnings, in Generic types check Ignore unavoidable generic type problems due to raw APIs.