wood burning stoves 2.0
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

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
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: 4680

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: 4680

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

Joined: Oct 27, 2005
Posts: 19844

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
I agree. Here's the link: http://aspose.com/file-tools
subject: Can't find method using reflection