Reputation: 59
On java reflection tutorial page, the example has this snippet
if ((pType.length != 1) ||
Locale.class.isAssignableFrom(pType[0].getClass())) {
continue;
}
"Also, Class.isAssignableFrom() is used to determine whether the parameters of the located method are compatible with the desired invocation."
I thought the snippet was trying to find the method with Locale as the parameter. However, it's trying to look for Locale.class.isAssignableFrom(pType[0].getClass()) and skip. The funny thing is that the example works as described because Locale.class.isAssignableFrom(pType[0].getClass()) returns false when pType[0] is Locale.
Does anybody know why would Locale.class.isAssignableFrom(pType[0].getClass()) return false when pType[0] is Locale, and what is the proper way to check if the parameter for the method is Locale?
Thanks in advance for any help.
Upvotes: 0
Views: 224
Reputation: 38
I think this maybe right:
if ((pType.length != 1) || !Locale.class.isAssignableFrom((Class<?>) pType[0])) {
continue;
}
Upvotes: 0
Reputation: 5591
It looks like the example is flawed. The call to Locale.class.isAssignableFrom(pType[0].getClass())
is returning false because Type.getClass()
is returning Class
and not Locale
. This means that the if-statement will never be true since Type's getClass()
method always seems to return Class
.
If you add a new method to the class like this:
private boolean testBar2(int l) { return true; }
this will cause the program to throw an IllegalArgumentException because it will call testBar2 even though the type is not Locale.
Type
is an interface and calling pType[0].getClass()
is asking to get the class of pType[0]
, which is Class
(not Locale
) because Class
implements the Type
interface. To find out what class the Type
object represent we can only use its toString
method and see if it is "class java.util.Locale" because there are no Type-specific methods in the interface.
In short, I think their use of isAssignableFrom
seems invalid here, and thus their discussion about its use is wrong also.
Upvotes: 1