• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Finding field defined in parent class

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are you using reflection at all???
 
Morning came much too soon and it brought along a friend named Margarita Hangover, and a tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic