Why do I have to explicitly cast sometimes for varargs?
- by Daniel Lew
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?