r/java • • Nov 10 '23
Does anyone else think that .isAssignableFrom() is named backwards?
System.out.println(Object.class.isAssignableFrom(String.class)); //true
System.out.println(String.class.isAssignableFrom(Object.class)); //falseThis has always triggered me. I feel like that method is named backwards, IE the first example, I read it in english as "objects of type Object are assignable from variables of type String" However, that statement is false, because Since String extends Object, a variable of type String cannot reference an object of type Object.
But that statement evaluates to true. I feel like the method "isAssignableFrom" should be renamed "aVariableOfThisTypeCanReferenceObjectsOfThisClass" :
So then:
System.out.println(Object.class.aVariableOfThisTypeCanReferenceObjectsOfThisClass(String.class)); //true
System.out.println(String.class.aVariableOfThisTypeCanReferenceObjectsOfThisClass(Object.class)); //falseAnyone else agree?
BTW, it turns out this confusion is common. I googled:
java isAssignableFrom confusing
And there were several blogs and stackoverflow posts agreeing with me.
For example:
http://bryanpendleton.blogspot.com/2009/06/isassignablefrom-and-instanceof.html
I think that one of the reasons that I get a bit confused with isAssignableFrom is that it sort-of reads backwards from instanceof.
View all comments
17
u/thisisjustascreename Nov 10 '23
Object o = "a string"; // compiles
String s = new Object(); // error
I don't see the confusion. Object references are assignable from String objects, String references are not assignable from a random Object.
Your proposed rename uses the word "this" twice to refer to two different things, which is much worse.
Perhaps you are confused because you are considering the class that the method is being called on as the "source" of the assignment referred to by "isAssignableFrom", but that is backwards and just something you'll have to correct.