• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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: 24204
44
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
  • 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???
 
Where all the women are strong, all the men are good looking and all the tiny ads are above average:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic