Friday, March 4, 2011

Testing linear class relationship

I'm calling this linear class relationship, but correct me if I'm wrong. I'm looking to test whether or not the class of object A is an ancestor or descendant of object B's class.

For example, AbstractCollection is linearly related to both Object and ArrayList. However, ArrayList is not linearly related to Vector.

My first stab 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 an appropriate check?

From stackoverflow
  • Your test works. I prefer the symmetric check:

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

0 comments:

Post a Comment