S
Soefara
Dear all,
I'm really struggling to see what's wrong with the following
method which uses reflection to dynamically call a method
of an object.
It compiles fine, but when I pass it a String instance and
the methodName "toUpperCase" or "toLowerCase" it reports
no such method found. It does however work with "toString" !
The same thing happens with any other class objects I pass
it. About the only methodName that is understood is "toString".
Anything else will return the "no such method" error
Am I missing something obvious here?
-------------------------------------------------------------
// Call a method of an object with no arguments/parameters.
public static Object callMethod(Object obj, String methodName) {
Class c = Object.class;
Object result = null;
try {
Method m = c.getMethod(methodName, new Class[]{});
result = m.invoke(obj, new Object[]{} );
}
catch(java.lang.NoSuchMethodException e) {
System.out.println("Error - No such method: \n" + e.getMessage());
}
catch(java.lang.IllegalAccessException e) {
System.out.println("Error - Illegal access: \n" + e.getMessage());
}
catch (java.lang.reflect.InvocationTargetException e) {
System.out.println("Error - Reflection error : \n" + e.getMessage());
}
return result;
}
-------------------------------------------------------------
Thank you very much in advance,
Soefara
I'm really struggling to see what's wrong with the following
method which uses reflection to dynamically call a method
of an object.
It compiles fine, but when I pass it a String instance and
the methodName "toUpperCase" or "toLowerCase" it reports
no such method found. It does however work with "toString" !
The same thing happens with any other class objects I pass
it. About the only methodName that is understood is "toString".
Anything else will return the "no such method" error
Am I missing something obvious here?
-------------------------------------------------------------
// Call a method of an object with no arguments/parameters.
public static Object callMethod(Object obj, String methodName) {
Class c = Object.class;
Object result = null;
try {
Method m = c.getMethod(methodName, new Class[]{});
result = m.invoke(obj, new Object[]{} );
}
catch(java.lang.NoSuchMethodException e) {
System.out.println("Error - No such method: \n" + e.getMessage());
}
catch(java.lang.IllegalAccessException e) {
System.out.println("Error - Illegal access: \n" + e.getMessage());
}
catch (java.lang.reflect.InvocationTargetException e) {
System.out.println("Error - Reflection error : \n" + e.getMessage());
}
return result;
}
-------------------------------------------------------------
Thank you very much in advance,
Soefara