检查 javax.lang.model.type.TypeMirror 是原始类型

Check javax.lang.model.type.TypeMirror is a primitive type

有什么方法可以检查 javax.lang.model.type.TypeMirror 是原始类型吗?我试过 instanceof PrimitiveType 但这总是会产生 true,因为 PrimitiveType 扩展了 TypeMirror。

感谢您的帮助。

https://docs.oracle.com/javase/7/docs/api/javax/lang/model/type/TypeMirror.html

To implement operations based on the class of an TypeMirror object, either use a visitor or use the result of the getKind() method. Using instanceof is not necessarily a reliable idiom for determining the effective class of an object in this modeling hierarchy since an implementation may choose to have a single object implement multiple TypeMirror subinterfaces.

尝试调用 getKind() 而不是 instanceOf

如果你有TypeMirror object, you can get the kind of this type (TypeKind) with the getKind() method and then use the isPrimitive()方法。

if(typeMirror.getKind().isPrimitive()){
     //It's a primitive type
}

有2个选项:

检查它是否是原始类型

typeMirror.getKind().isPrimitive()

或者如果它是 PrimitiveType 的实例,则使用访问者来执行操作

typeMirror.accept(new SimpleTypeVisitor6<P, R>() {
    @Override R visitPrimitive(PrimitiveType t, P p) {
      //do something with primitive type t
    }
}, null);