Linear class relationship check

I call this a linear class relationship, but correct me if I'm wrong. I am trying to check if an object's class is an A

ancestor or descendant of an object's class B

.

For example, AbstractCollection

linearly related both to Object

and from ArrayList

. However, ArrayList

it has no linear relationship with Vector

.

My first hit was:

// ...Assume objects A and B were declared...

Class<? extends Object> Aclass = A.getClass();
if (Aclass.isAssignableFrom(B.getClass()) || Aclass.isInstance(B)) {
    // Their types are linearly related, at the least
}

      

Is this a valid test?

0


source to share


1 answer


Your test is working. I prefer symmetric validation:



if (a.getClass().isInstance(b) || b.getClass().isInstance(a)) { 
}

      

+2


source







All Articles