dynamic method call using reflection only works with certain methods?

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
 
R

Robert Olofsson

Soefara ([email protected]) wrote:
: public static Object callMethod(Object obj, String methodName) {
: Class c = Object.class;
: Object result = null;
: try {
: Method m = c.getMethod(methodName, new Class[]{});

Hmm, c is the class Object, not the class of obj. That is the
misstake right?

Object does have a toString, but it does not have a toUpperCase.

/robo
 
P

pete kirkham

You also will need to specify the types and classes of the parameters if
you are trying to find a method which takes any.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top