• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't find method using reflection

 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5128
11
Java Netbeans IDE Opera
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Darryl Burke
Bartender
Posts: 5128
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, "".getClass() is better written as String.class.
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic