Convert Eclipse JDT ITypeBinding to a Type

abstract-syntax-tree, eclipse, eclipse-jdt, java

Solution

I've just found an alternative solution which might be preferable. You could use org.eclipse.jdt.core.dom.rewrite.ImportRewrite, which manages import statements of a compilation unit. Using Type addImport(ITypeBinding,AST), you can create a new Type node taking existing imports into account and adding new ones if necessary.

Problem

I'm looking for a general way to convert an `org.eclipse.jdt.core.dom.ITypeBinding` instance to an `org.eclipse.jdt.core.dom.Type` instance. Although I feel there should be some API call to do this, I cannot locate one. There appear to be various ways to do this manually depending on the specific type. Is there any general way to take an `ITypeBinding` and get a `Type` without all of these special cases? Taking a `String` and returning a `Type` would also be acceptable. Update From the response so far, it appears I do have to handle all these special cases. Here is a first attempt at doing so. I'm sure this is not completely correct so scrutiny is appreciated: ``` 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)); } ```

Original source