• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finding field defined in parent class

 
Ash Kondhalkar
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have one child class(let us say "c1") which inherits from parent class(let us say "p1"). p1 has one public field as "userID".
I have object "objectC1" of class c1. I am using a reflection method to get a field "userID" as below,

objectC1.getClass().getDeclaredField("userID");
It comes back with exception that
"java.lang.NoSuchFieldException: userID".

This method works fine for all fields declared in class c1.

Do we have a method to find out what are the parent classes for a particular class? So that I can fire the above method on each one of them and get the Field userID.
Or there is any other way? Kindly suggest.

Regards
Ashwin
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use "getField" instead of "getDeclaredField"; this will return inherited public fields. If the inherited field is not public, then use getSuperclass() to get the class object for p1, and then use getDeclaredField on it.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems to me you can get what you want using Class.getSuperclass().

However, you can access public fields of superclass without going to the superclass Class object. Use Class.getField(), rather than class.getDeclaredField(). Read the API to see the difference.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using reflection at all???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic