将Eclipse JDT ITypeBinding转换为Type

Jak*_*obb 5 java eclipse abstract-syntax-tree eclipse-jdt

我正在寻找将org.eclipse.jdt.core.dom.ITypeBinding实例转换为实例的一般方法org.eclipse.jdt.core.dom.Type.虽然我觉得应该有一些API调用来做到这一点,但我找不到一个.

根据具体类型,似乎有多种方法可以手动执行此操作.

ITypeBinding如果Type没有所有这些特殊情况,是否有任何一般方法可以获得并得到一个?拿a String和返回a Type也是可以接受的.

更新

从目前为止的反应来看,似乎我必须处理所有这些特殊情况.这是第一次尝试这样做.我确信这不是完全正确的,所以请仔细审查:

public static Type typeFromBinding(AST ast, ITypeBinding typeBinding) {
    if( ast == null ) 
        throw new NullPointerException("ast is null");
    if( typeBinding == null )
        throw new NullPointerException("typeBinding is null");

    if( typeBinding.isPrimitive() ) {
        return ast.newPrimitiveType(
            PrimitiveType.toCode(typeBinding.getName()));
    }

    if( typeBinding.isCapture() ) {
        ITypeBinding wildCard = typeBinding.getWildcard();
        WildcardType capType = ast.newWildcardType();
        ITypeBinding bound = wildCard.getBound();
        if( bound != null ) {
            capType.setBound(typeFromBinding(ast, bound)),
                wildCard.isUpperbound());
        }
        return capType;
    }

    if( typeBinding.isArray() ) {
        Type elType = typeFromBinding(ast, typeBinding.getElementType());
        return ast.newArrayType(elType, typeBinding.getDimensions());
    }

    if( typeBinding.isParameterizedType() ) {
        ParameterizedType type = ast.newParameterizedType(
            typeFromBinding(ast, typeBinding.getErasure()));

        @SuppressWarnings("unchecked")
        List<Type> newTypeArgs = type.typeArguments();
        for( ITypeBinding typeArg : typeBinding.getTypeArguments() ) {
            newTypeArgs.add(typeFromBinding(ast, typeArg));
        }

        return type;
    }

    // simple or raw type
    String qualName = typeBinding.getQualifiedName();
    if( "".equals(qualName) ) {
        throw new IllegalArgumentException("No name for type binding.");
    }
    return ast.newSimpleType(ast.newName(qualName));
}
Run Code Online (Sandbox Code Playgroud)

rue*_*ste 2

我刚刚找到了一个可能更好的替代解决方案。您可以使用org.eclipse.jdt.core.dom.rewrite.ImportRewrite,它管理编译单元的导入语句。使用 Type addImport(ITypeBinding,AST),您可以创建一个新的 Type 节点,同时考虑现有导入并在必要时添加新导入。