I have a 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 complicated, but the idea is it. To call doMethod, I am doing something like this:
Method m = MyClass.class.getMethod("myMethod", String.class);
String result = (String)doMethod(m, "Hello");
This works fine for me (a variable number of arguments and all). The thing that annoys me is the necessary cast in Stringthe caller. . Since it myMethoddeclares that it returns String, I would like it to doMethodbe smart enough to change its return type should also be String. Is there a way to use Java generics to do something like this?
String result = doMethod(m, "Hello");
int result2 = doMethod(m2, "other", "args");
source
share