为何针对int原始类型调用directSupertypes(TypeMirror)返回空List?
解决
directSupertypes处理int类型返回空列表的问题 当调用javax.lang.model.util.Types#directSupertypes(TypeMirror)处理代表int的TypeMirror时,返回空列表的核心原因是:该API的实现(如javac中的默认实现)并未将JLS定义的基本类型拓宽子类型关系纳入处理逻辑。
JLS中明确int的直接超类型是long,但directSupertypes方法主要针对引用类型的继承/实现关系设计,对基本类型的子类型关系不做识别,因此返回空列表。
手动实现基本类型的直接超类型获取
要得到符合JLS预期的结果,需要手动维护基本类型的子类型映射,并在代码中单独处理:
- 定义基本类型到直接超类型的映射:
private static final Map<TypeKind, TypeKind> PRIMITIVE_SUPER_TYPE_MAP = Map.of( TypeKind.BYTE, TypeKind.SHORT, TypeKind.SHORT, TypeKind.INT, TypeKind.INT, TypeKind.LONG, TypeKind.LONG, TypeKind.FLOAT, TypeKind.FLOAT, TypeKind.DOUBLE );
- 封装方法获取直接超类型:
public List<TypeMirror> getDirectSupertypesWithPrimitives(Types types, TypeMirror type) { List<TypeMirror> superTypes = new ArrayList<>(); if (type.getKind().isPrimitive()) { TypeKind superKind = PRIMITIVE_SUPER_TYPE_MAP.get(type.getKind()); if (superKind != null) { superTypes.add(types.getPrimitiveType(superKind)); } } else { superTypes.addAll(types.directSupertypes(type)); } return superTypes; }
调用这个方法处理int类型的TypeMirror时,就会返回包含代表long的PrimitiveType元素的列表,符合JLS的定义。
内容的提问来源于stack exchange,提问作者Laird Nelson
相关产品推荐
相关产品推荐

