Why do I have to explicitly cast sometimes for varargs?
Posted
by
Daniel Lew
on Stack Overflow
See other posts from Stack Overflow
or by Daniel Lew
Published on 2011-01-14T21:48:26Z
Indexed on
2011/01/14
21:53 UTC
Read the original article
Hit count: 191
java
I've got a Class that uses reflection a lot, so I wrote a method to help out:
private <T> T callMethod(String methodName, Class[] parameterTypes, Object[] args) {
try {
Class c = mVar.getClass();
Method m = c.getMethod(methodName, (Class[]) parameterTypes);
return (T) m.invoke(mVar, args);
}
// Insert exception catching here [...]
}
This worked well for any method that had parameters, however I had to explicitly cast parameterTypes
to Class[]
in order for this to work for methods with no parameters (e.g., callMethod('funName', null, null);
). I've been trying to figure out why this is the case.
It seems to me that if parameterTypes
, when null, had no concept of what type it is (Class[]
), then I'd need to cast it for getMethod()
. But if that's the case, why is getMethod()
able to tell the difference between null
, and (Class[]) null
when the method is invoked?
© Stack Overflow or respective owner