obj = obj.getClass().getSuperclass().cast(obj);

This line does not do what you expect it to do. Casting an Object does not actually change it, it just tells the compiler to treat it as something else.

E.g. you can cast a List to a Collection, but it will still remain a List.

However, looping up through the super classes to access fields works fine without casting:

Class<?> current = yourClass;
while(current.getSuperclass()!=null){ // we don't want to process Object.class
    // do something with current's fields
    current = current.getSuperclass();
}

BTW, if you have access to the Spring Framework, there is a handy method for looping through the fields of a class and all super classes:
ReflectionUtils.doWithFields(baseClass, FieldCallback)
(also see this previous answer of mine: Access to private inherited fields via reflection in Java)

Answer from Sean Patrick Floyd on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › retrieve fields from a java class using reflection
Retrieve Fields from a Java Class Using Reflection | Baeldung
January 4, 2026 - The Class::getFields() method approaches our goal by returning all public fields of a class and its superclasses, but not the protected ones.
🌐
TutorialsPoint
tutorialspoint.com › get-all-declared-fields-from-a-class-in-java
Get all declared fields from a class in Java
June 25, 2020 - Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object.
🌐
Dev.java
dev.java › learn › reflection › fields
Reading and Writing Fields - Dev.java
July 19, 2024 - A Field object lets you get more information on the corresponding field: its type and its modifiers, and enables you to get the value of this field for a given object, and to set it. This section also covers how you can discover fields in a class. There are two categories of methods provided in Class for accessing fields. First, you can look for a specific field. These methods suppose you have a name for the field you are looking for. Second, you can look for all the fields that are declared in this class, or for the fields declared in this class, and all its super classes, up to the Object class.
🌐
Kodejava
kodejava.org › how-do-i-get-fields-of-a-class-object
How do I get fields of a class object? - Learn Java by Examples
May 21, 2023 - package org.kodejava.lang.reflect; import java.util.Date; import java.lang.reflect.Field; public class GetFields { public Long id; protected String name; private Date birthDate; Double weight; public static void main(String[] args) { GetFields ...
🌐
Baeldung
baeldung.com › home › java › core java › get all record fields and its values via reflection
Get All Record Fields and Its Values via Reflection | Baeldung
January 16, 2024 - The RecordComponent class provides information about a component of a record class. Moreover, the Class class provides the getRecordComponents() method to return all components of a record class if the class object is a Record instance.
🌐
Avajava
avajava.com › tutorials › lessons › how-do-i-list-the-declared-fields-of-a-class.html
How do I list the declared fields of a class?
Account Suspended · This Account has been suspended · Contact your hosting provider for more information
🌐
TutorialsPoint
tutorialspoint.com › get-the-list-of-all-declared-fields-in-java
Get the list of all declared fields in Java
June 25, 2020 - The list of all declared fields can be obtained using the java.lang.Class.getDeclaredFields() method as it returns an array of field objects. These field objects include the objects with the public, private, protected and default access but not the inherited fields.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java class getfields method
Java Class getFields Method
September 1, 2008 - The following example shows the usage of java.lang.Class.getFields() method. In this program, we've retrieved class of java.awt.Label and then using getFields() method, all fields are retrieved and printed them.
🌐
Simplesolution
simplesolution.dev › java-get-all-field-names-of-class
Java Get All Field Names of Class
... import java.util.List; public ... baseEntity = new BaseEntity(); List<String> allFieldNames = ClassUtils.getAllFieldNames(baseEntity.getClass()); allFieldNames.forEach(System.out::println); } } The output as below...
🌐
GitHub
gist.github.com › 899b2f09ac9108436d5d
Getting All fields(including inherited) from a JAVA class[POJO] · GitHub
Getting All fields(including inherited) from a JAVA class[POJO] - Getting All fields of Java Class
🌐
Coderanch
coderanch.com › t › 373499 › java › reflection-fields-public
Using reflection to get ALL fields, not just public ones (Java in General forum at Coderanch)
Also it's possible to get at the info in the private field using reflection, or if the class is Serializable you can write it to a file and see that the file contains data from private superclass fields. However these fields are still not considered accessible in the sense that you can access them by simply wrting the name of the field like you can for most other fields.
🌐
GeeksforGeeks
geeksforgeeks.org › java › class-getfields-method-in-java-with-examples
Class getFields() method in Java with Examples - GeeksforGeeks
July 12, 2025 - Exception This method throws SecurityException if a security manager is present and the security conditions are not met. Below programs demonstrate the getFields() method. Example 1: ... // Java program to demonstrate getFields() method import ...
🌐
CodingTechRoom
codingtechroom.com › question › retrieve-java-class-fields
How to Retrieve All Class Fields in Java, Including Private and Inherited Fields - CodingTechRoom
private void listAllFields(Object obj) { List<Field> fieldList = new ArrayList<>(); Class<?> tmpClass = obj.getClass(); while (tmpClass != null) { fieldList.addAll(Arrays.asList(tmpClass.getDeclaredFields())); tmpClass = tmpClass.getSuperclass(); } // Process fieldList as needed } In Java, accessing class fields can be crucial for reflection tasks, especially when you need to examine all fields, including those that are private or inherited. The following guide provides an expert approach to listing all fields from a class instance effectively, making use of Java Reflection API.
Top answer
1 of 2
2

Here's a simple way that inspects class declared fields:

static Set<Field> getFields(Class<?> cls) {
    Set<Field> set = new HashSet<>();

    for (Field f : cls.getDeclaredFields()) {
        set.add(f);

        //a filter to avoid standard classes. Update accordingly
        if (f.getType().getName().startsWith("com.foo.bar")) {
            set.addAll(getFields(f.getType()));
        }
    }

    return set;
}

And a simple call:

public static void main(String[] args) {
    Set<Field> all = getFields(Employee.class);
    for (Field f : all) {
        System.out.println(String.format("%s.%s", 
             f.getDeclaringClass().getSimpleName(), f.getName()));
    }
}

With your example classes, the above prints:

Employee.firstName
Employee.address
Address.street
Address.streetNum
Employee.id

And here's an equivalent Java8+ version (only inspecting 2 levels of the tree):

Stream.of(Employee.class.getDeclaredFields())
        .flatMap(f -> Stream.concat(Stream.of(f), 
                Stream.of(f.getType().getDeclaredFields())))
        .filter(f -> f.getDeclaringClass()
                      .getPackage()
                      .getName()
                      .startsWith("com.foo.bar"))
        .map(f -> String.format("%s.%s", 
                    f.getDeclaringClass().getSimpleName(), f.getName()))
        .forEach(System.out::println);

The filter above is used to limit inspected classes to those in the current package (change accordingly). Without it, one gets String's fields, etc.

You may also want to call distinct() to remove duplicates if they may show up.

2 of 2
1

Thank you all, I created a recursive function that does the trick. The function is the following

private void getClassFields(final Class c,final List<String> fields) throws ClassNotFoundException {
    for(Field f : c.getDeclaredFields()){
        if(f.getType().getName().contains("foo.bar")){
            getClassFields(Class.forName(f.getType().getName()),fields);
        }else {
            fields.add(f.getName());
        }
    }
}
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › reflect › class › getFields.html
Identifying Class Fields
Note that the program first retrieves the Field objects for the class by calling getFields, and then invokes the getName and getType methods on each of these Field objects. import java.lang.reflect.*; import java.awt.*; class SampleField { public static void main(String[] args) { GridBagConstraints g = new GridBagConstraints(); printFieldNames(g); } static void printFieldNames(Object o) { Class c = o.getClass(); Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); } } } A truncated listing of the output generated by the preceding program follows:
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › class › classMembers.html
Discovering Class Members (The Java™ Tutorials > The Reflection API > Classes)
Given a class name and an indication of which members are of interest, the ClassSpy example uses the get*s() methods to determine the list of all public elements, including any which are inherited. import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.refle...