A subtype is established when a class is linked by means of extending or implementing. Subtypes are also used for generics.
How can I differentiate subtyping from subclasses?
In Java, subclassing is a kind of subtyping.
There are a number of ways Java allows subtyping:
class A extends B
, A
is a subtype of B
because B b = new A(...);
is ok.interface A extends B
, A
is a subtype of B
because B b = new A() { ... }
is ok.class A extends B
, A[]
is a subtype of B[]
because B[] b = new A[0]
is ok.class A implements B
, A
is a subtype of B
because B b = new A(...)
is ok.It sounds like you want a way to distinguish one from the others. The below should do that.
static boolean isSubclass(Class<?> a, Class<?> b) {
return !b.isArray() && !b.isInterface() && b.isAssignableFrom(a);
}
It won't handle subtyping of generic classes due to type erasure though. Class
instances don't carry type parameters at runtime so there is no way to distinguish the runtime type of a new ArrayList<String>()
from a new ArrayList<Integer>()
.