This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 4646
    
    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: 4523
    
    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: 4523
    
    5

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

Joined: Oct 27, 2005
Posts: 19656
    
  18

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
 
Similar Threads
jasper reports with subreports
Deadlock testing class for B&S 2.2.1
Help needed in ModelMBean descriptors
System.out.println Not printed when using ANT from a java program
Doubt in Overloading