我正在寻找将 org.eclipse.jdt.core.dom.ITypeBinding
实例转换为 org.eclipse.jdt.core.dom.Type< 的通用方法
实例。虽然我觉得应该有一些 API 调用来执行此操作,但我找不到。
根据具体类型,似乎有多种手动执行此操作的方法。
有没有通用的方法来获取 ITypeBinding
并获得 Type
而无需所有这些特殊情况?采用 String
并返回 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));
}
最佳答案
我刚刚找到了一个可能更可取的替代解决方案。你可以使用 org.eclipse.jdt.core.dom.rewrite.ImportRewrite ,它管理编译单元的导入语句。使用 Type addImport(ITypeBinding,AST),您可以创建一个新的 Type 节点,将现有的导入考虑在内,并在必要时添加新的导入。
关于java - 将 Eclipse JDT ITypeBinding 转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091791/