TypeMirror 的 isSubtype 和 isAssignable 之间的区别
在实用程序接口的文档中 类型< /a>,其中一个实例必须由编译器提供给 Java SE 6 或 7 的注释处理器,有两种方法对我正在处理的代码片段感兴趣。我需要检查字段的类型是否是从特定抽象类继承的类型。似乎适用的两种方法是 isAssignable
和 isSubtype
。但我不确定使用其中的哪一个。
我已经检查了上述文档中引用的 Java 语言规范的那些部分。我理解子类型和赋值转换概念之间的区别(至少我认为我这样做)。除非我弄错了,否则 java.lang.Short
不会是基元 long
的子类型(子类型是在基元之间定义的,但不是跨类和基元的),但是由于拆箱和扩大转换,它可以这样分配:
final Short s = 0;
final long l = s;
但是,我仍然不确定在我的情况下使用的最佳方法是什么。检查子类型似乎比可分配性更严格、更可取,但是当涉及到类时,感觉好像一个子类型自动暗示了另一个子类型。
长版简短:当比较的 TypeMirror 都用于类(不是接口或枚举)时, isAssignable 和 isSubtype 是否等效?
In the documentation for the utility interface Types, of which an instance must be made available to an annotation processor for Java SE 6 or 7 by the compiler, there are two methods which interest me for a code snippet I'm working on. I need to check if a field's type is a type that inherits from a specific abstract class. The two methods that seem applicable are isAssignable
and isSubtype
. But I'm not certain which of these to use.
I've checked those parts of the Java Language Specification that are referenced in the above documentation. I understand the difference between the concepts of subtypes and assignment conversion (at least I think I do). Unless I'm mistaken, java.lang.Short
would not be a subtype of the primitive long
(subtyping is defined amongst primitves, but not across classes and primitives), but it can be assigned like so thanks to unboxing and widening conversion:
final Short s = 0;
final long l = s;
However, I'm still not certain what the best method to use would be in my case. Checking for a subtype seems more strict and preferable than assignability, but when it comes to classes it feels as if one automatically implies the other.
Long version short: are isAssignable
and isSubtype
equivalent when the compared TypeMirrors are both for classes (not interfaces or enums)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我们进行引用分配,则在这种情况下适用的唯一转换是扩大引用转换(当然,恒等转换除外)。现在我们有以下执行规则:
这意味着如果您只考虑类,那么讨论子类型或可分配性并不重要。所以是的,在这种情况下提到的方法是等效的。
If we take assignment of references, the only conversion which applies in this case is the widening reference conversion (except for the identity conversion, of course). Now we have the following rules for carrying it out:
This means that if you consider only classes, it doesn't matter whether you talk about subtypes or assignability. So yes, the mentioned methods are equivalent in this case.