Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java reflection to invoke parent class method

 
Edward Chen
Ranch Hand
Posts: 798
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the parent class, I have a public method, then in the child class, I try to access it using java reflection, it doesn't work.

How to work it out ?

Thanks
 
Mehar Simhadri
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I am able to access the parent methods also in the child using reflection

Can you elaborate more on what are you trying to do...

 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reflection is definitely not a beginner's subject, so I'll move the discussion to a more appropriate forum. Also, please note that ItDoesntWorkIsUseless. If you told us what you tried, and what exactly did or did not happen, we'd be in a much better position to help.
 
Rob Spoor
Sheriff
Pie
Posts: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which method are you using to get the method?

getDeclaredXXX only returns members actually declared in that class; public methods and fields of the parent class are not found.

getXXX only returns public members in that class, also those declared in the parent class (except when overridden / hidden). Non-public members are not found.
 
Marky Vasconcellos
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote it's now... don't know if its works.

 
Marky Vasconcellos
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote it's now... don't know if its works.



And if you want access and invoke the private Methods you only need add this line before "return m;"
 
Rob Spoor
Sheriff
Pie
Posts: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marky Vasconcellos wrote:I wrote it's now... don't know if its works.


That solution would work for all methods, not only public ones. There is one "but" though: getMethod and getDeclaredMethod never return null, but throw a NoSuchMethodException instead. So your code would be this:

Of course you can wrap the NoSuchFieldException in a RuntimeException if you don't want the checked exception:

Just be careful - your method only looks for methods without a parameter.


Now, as I've said before, if you only need to look for public methods, it's much simpler:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic