I have some code like this:
Object doMethod(Method m, Object... args) throws Exception {
Object obj = m.getDeclaringClass().getConstructor().newInstance();
return m.invoke(obj, args);
}
The code I use is a little more complex, but that’s the idea of it. To invoke doMethod I do something like this:
Method m = MyClass.class.getMethod("myMethod", String.class);
String result = (String)doMethod(m, "Hello");
This works just fine for me (variable number of arguments and all). The thing that irks me is the necessary cast to String in the caller. Since myMethod declares that it returns a String, I’d like doMethod to be smart enough to change its return type to also be String. Is there some way of using Java generics to accomplish something like this?
String result = doMethod(m, "Hello");
int result2 = doMethod(m2, "other", "args");
Sure,
One is idly curious about the architecture that calls for such a thing to be done, but that’s well out of scope 🙂
If you don’t like that you can also leave off the binding of returnType and the compiler will automatically cast it to whatever you’re assigning the return type to. e.g., this is legal:
The cast will be to whatever you are attempting to assign it to, but I think most people would consider it suspect.