I'm doing some weird reflection stuff to get around wrapping a whole bunch of methods in a class. The java docs suggest that null would be the solution, but it fails with NoSuchMethodException.
public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException If parameterTypes is null, it is treated as if it were an empty array.
To begin with I'm trying:
private <T> T invokeWrappedFunction(Object instance, String methodName, Object... args) { try{ Method m = instance.getClass().getMethod(methodName, (args == null ? null : args.getClass())); return (T) m.invoke(instance, args); } catch(Exception e) { //This is an example, you're lucky I even acknowledged the exception! } } Now eventually there will be lots of extra functionality in there and instance isn't an unknown type so I can do helpful stuff on failures and such. The real question is how do I get the getMethod working?
args.getClass()so maybe my cleverness is hubris :(args.getClass(). It will return the class of an object array which is an instance ofClass, notClass[]. You need to construct a newClassarray and fill it with eacharg.getClass(). Even then, though, I'm not sure that will work with any polymorphism/subclassing becausegetClass()may not correspond to the formal parameter list.Class.getComponentType();See updated answer below.nullworks just fine, btw.)