File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Finding field defined in parent class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finding field defined in parent class" Watch "Finding field defined in parent class" New topic

Finding field defined in parent class

Ash Kondhalkar
Ranch Hand

Joined: Jun 14, 2006
Posts: 43

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,

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.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Why are you using reflection at all???

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Finding field defined in parent class
It's not a secret anymore!