Question

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)?

Was it helpful?

Solution

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:

A widening reference conversion exists from any type S to any type T, provided S is a subtype (§4.10) of T.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top