File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Can't find method using reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can Watch "Can New topic

Can't find method using reflection

Pat Farrell

Joined: Aug 11, 2007
Posts: 4659

I can't seem to get Class getMethod to work. It doesn't find the method, but I am sure its there, as I can print out the method
using this.getClass().getDeclaredMethods().

Here is a test program:

If I run the program, it fails with "no such method as setUser"

The complete resulting output is:

Is this just a bug in my code? or am I approaching this problem backwards?
Darryl Burke

Joined: May 03, 2008
Posts: 4752

The API for getMethod(...) starts (stress added)
Returns a Method object that reflects the specified public member method

Your class doesn't have a public member method setUser(...). It's package-private.

luck, db
There are no new questions, but there may be new answers.
Darryl Burke

Joined: May 03, 2008
Posts: 4752

Also, "".getClass() is better written as String.class.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19898

Darryl is right (in both posts). To find non-public methods, use getDeclaredMethod instead. If I switch to using that then the exception is not thrown.

How To Ask Questions How To Answer Questions
It is sorta covered in the JavaRanch Style Guide.
subject: Can't find method using reflection