File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can Watch "Can New topic
Author

Can't find method using reflection

Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

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
Bartender

Joined: May 03, 2008
Posts: 4642
    
    5

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
Bartender

Joined: May 03, 2008
Posts: 4642
    
    5

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

Joined: Oct 27, 2005
Posts: 19720
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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