Skip to main content

isAssignableFrom & isAssignableTo?

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
matthewadams
Offline
Joined: 2003-10-08

Hi all,
I have a dumb question, because I'm wondering if it's just me.
I've been using Java since before JDK 1.0 (long time), and whenever I use the method Class#isAssignableFrom(Class), I get confused. In order to understand it, I always have to flip it around and consider whether the given Class can be assigned to a variable of the type of the Class whose method is being called. Consider the following example.

=====
public interface MyInterface { /* ... */ }
=====
public class MyClass implements MyInterface { /* ... */ }
=====
public class SomeClassUsingReflection {
  public void useMethodIsAssignableFrom() {
    Class i = MyInterface.class;
    Class c = MyClass.class;
    boolean myClassImplementsMyInterface = i.isAssignableFrom(c); // always trips me up
  }
}

Whenever I'm reading or writing code like i.isAssignableFrom(c), I have to read backward, essentially thinking this instead: c.isAssignableTo(i). Then I'm clear and can move on.
So here's my question. Am I the only person on the planet who trips on isAssignableFrom and reverses it to isAssignableTo in order to understand it? How about adding this method to Class just as a convenience method for readability?
public void isAssignableTo(Class that) { return that.isAssignableFrom(this); }

-matthew

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
hamsterofdeath
Offline
Joined: 2006-02-14

i was confused too, but then i made up that rule:
do it: Type t = someObj
check it : tClass.isAssignableFrom(someObjClass)
it's the way you'd write the assignment expression. the other way, the one you prefer, is "can i assign YOU to THAT"? which feels more OO-like to me
i bet there would be a lot less confusion if the method would have been named "isClassOrSuperClassOf"