首页 > 解决方案 > 用于 ImmutableSet 和 java.lang.Iterable 的 TypeMirror isSubtype 和 isAssignable

问题描述

我无法理解子类型和可分配之间的区别。

给定参数是 ImmutableSet 类型,我有以下代码来检查 ImmutableSet 是子类型还是可分配的:

      boolean isAssignable =
          types.isAssignable(
              types.erasure(parameters.asType()),
              elements.getTypeElement(Iterable.class.getCanonicalName()).asType());

      boolean isSubtype =
          types.isSubtype(
              types.erasure(parameters.asType()),
              elements.getTypeElement(Iterable.class.getCanonicalName()).asType());

      processingEnv.getMessager().printMessage(Kind.NOTE, "Type " + types.erasure(parameters.asType())
          + " is " + (isSubtype ? "" : " not ") + " a subtype of " + Iterable.class.getCanonicalName());

      processingEnv.getMessager().printMessage(Kind.NOTE, "Type " + types.erasure(parameters.asType())
          + " is " + (isAssignable ? "" : " not ") + " a assignable of " + Iterable.class.getCanonicalName());

输出如下:

Type com.google.common.collect.ImmutableSet is not a subtype of java.lang.Iterable
Type com.google.common.collect.ImmutableSet is a assignable of java.lang.Iterable

我可以理解为什么 ImmutableSet 可以分配给 Iterable 接口,这很清楚。但是,我不明白为什么 ImmutableSet 不是 Iterable 的子类型。

我检查了其他类似的问题,但没有一个解释过这一点。任何人都可以帮忙吗?

标签: javareflectionannotation-processing

解决方案


推荐阅读