我正在寻找一种将org.eclipse.jdt.core.dom.ITypeBinding
实例转换为实例的通用方法org.eclipse.jdt.core.dom.Type
。虽然我觉得应该有一些 API 调用来做到这一点,但我找不到一个。
根据具体类型,似乎有多种手动执行此操作的方法。
在没有所有这些特殊情况的情况下,是否有任何一般的方法来获取ITypeBinding
和获取?Type
接受 aString
并返回 aType
也是可以接受的。
更新
从目前的回复来看,看来我确实必须处理所有这些特殊情况。这是这样做的第一次尝试。我敢肯定这并不完全正确,因此感谢您的审查:
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));
}