If you are using Java 8, you can do:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields).forEach(field -> {
        field.setAccessible(true);
        try {
            lines.add(field.getName() + " = " + field.get(this));
        } catch (final IllegalAccessException e) {
            lines.add(field.getName() + " > " + e.getClass().getSimpleName());
        }
    });

    return lines.toArray(new String[lines.size()]);
}

or to improve formatting:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields)
            .forEach(
                    field -> {
                        field.setAccessible(true);
                        try {
                            lines.add(field.getName() + " = " + field.get(this));
                        } catch (final IllegalAccessException e) {
                            lines.add(field.getName() + " > "
                                    + e.getClass().getSimpleName());
                        }
                    });

    return lines.toArray(new String[lines.size()]);
}

Note that this is adding to @EricStein's excellent answer on normal concatenation instead of StringBuilders.

(I'm just starting to look into Streams, so if this is bad, please comment on why)

Otherwise...

Just a small comment:

lineBuilder.append(" = ");
lineBuilder.append(value);

can easily be:

lineBuilder.append(" = ").append(value);

Same with:

lineBuilder.append(" > ");
lineBuilder.append(e.getClass().getSimpleName());

becomes:

lineBuilder.append(" > ").append(e.getClass().getSimpleName());

Also, I would use a simple array instead of an ArrayList:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    String[] lines = new String[fields.length];

    int index = 0;
    for (Field field : fields) {
        StringBuilder lineBuilder = new StringBuilder();

        lineBuilder.append(field.getName());

        field.setAccessible(true);

        try {
            Object value = field.get(this);

            lineBuilder.append(" = ");
            lineBuilder.append(value);
        } catch (IllegalAccessException e) {
            lineBuilder.append(" > ");
            lineBuilder.append(e.getClass().getSimpleName());
        }

        lines[index++] = lineBuilder.toString();
    }

    return lines;
}

EDIT: The above review, if not using Java 8, should be replaced by @EricStein's code.

Also, getFields() is a bad name. Try getFieldDescriptions().

Answer from TheCoffeeCup on Stack Exchange
Top answer
1 of 2
5

If you are using Java 8, you can do:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields).forEach(field -> {
        field.setAccessible(true);
        try {
            lines.add(field.getName() + " = " + field.get(this));
        } catch (final IllegalAccessException e) {
            lines.add(field.getName() + " > " + e.getClass().getSimpleName());
        }
    });

    return lines.toArray(new String[lines.size()]);
}

or to improve formatting:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields)
            .forEach(
                    field -> {
                        field.setAccessible(true);
                        try {
                            lines.add(field.getName() + " = " + field.get(this));
                        } catch (final IllegalAccessException e) {
                            lines.add(field.getName() + " > "
                                    + e.getClass().getSimpleName());
                        }
                    });

    return lines.toArray(new String[lines.size()]);
}

Note that this is adding to @EricStein's excellent answer on normal concatenation instead of StringBuilders.

(I'm just starting to look into Streams, so if this is bad, please comment on why)

Otherwise...

Just a small comment:

lineBuilder.append(" = ");
lineBuilder.append(value);

can easily be:

lineBuilder.append(" = ").append(value);

Same with:

lineBuilder.append(" > ");
lineBuilder.append(e.getClass().getSimpleName());

becomes:

lineBuilder.append(" > ").append(e.getClass().getSimpleName());

Also, I would use a simple array instead of an ArrayList:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    String[] lines = new String[fields.length];

    int index = 0;
    for (Field field : fields) {
        StringBuilder lineBuilder = new StringBuilder();

        lineBuilder.append(field.getName());

        field.setAccessible(true);

        try {
            Object value = field.get(this);

            lineBuilder.append(" = ");
            lineBuilder.append(value);
        } catch (IllegalAccessException e) {
            lineBuilder.append(" > ");
            lineBuilder.append(e.getClass().getSimpleName());
        }

        lines[index++] = lineBuilder.toString();
    }

    return lines;
}

EDIT: The above review, if not using Java 8, should be replaced by @EricStein's code.

Also, getFields() is a bad name. Try getFieldDescriptions().

2 of 2
2

For getFields(), String concatenation is a not-unreasonable alternative you can consider. For toString(), using delete() is probably easier to read than the conditional check, there's probably no real performance gain due to branch prediction. It is distinctly wrong to merge the two methods. getFields() is probably not the best name, since it doesn't actually return the fields. Good names are hard, and nothing is jumping immediately to mind.

public abstract class Component {

    private String[] getFields() {
        final List<String> lines = new ArrayList<>();    
        for (final Field field: this.getClass().getFields()) {
            field.setAccessible(true);
            try {
                lines.add(field.getName() + " = " + field.get(this));
            } catch (final IllegalAccessException e) {
                lines.add(field.getName() + " > " + e.getClass().getSimpleName());
            }
        }
        return lines.toArray(new String[lines.size()]);
    }

    @Override
    public final String toString() {
        final StringBuilder builder = new StringBuilder(this.getClass().getSimpleName());

        builder.append('(');

        for (final String field : this.getFields()) {
            builder.append(field);
            builder.append(", ");
        }
        builder.delete(builder.length() - 2, builder.length());

        builder.append(')');

        return builder.toString();
    }
}
🌐
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.
🌐
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.
Top answer
1 of 3
147

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Oracle tutorial on the subject.

That said, if that VO is a fullworthy Javabean, then the fields do not necessarily represent real properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans. There's even a built-in one provided by Java SE in the java.beans package.

BeanInfo beanInfo = Introspector.getBeanInfo(someObject.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
    Method getter = property.getReadMethod(); 
    if (getter != null) {
        Object value = getter.invoke(someObject);
        if (value != null) {
            System.out.println(property.getName() + "=" + value);
        }
    }
}
2 of 3
12

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

  • BeanInfo (JavaDoc)
  • Introspector.getBeanInfo(class) (JavaDoc)
  • Introspection (Sun Java Tutorial)
🌐
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 - There are three ways shown below ... void main(String[] args) { GetFields object = new GetFields(); Class<? extends GetFields> clazz = object.getClass(); // Get all object fields including public, protected, package and private ...
🌐
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 - Nevertheless, we can use the Class::getDeclaredFields method to get all declared fields. The getDeclaredFields() method returns an array of Field objects alongside all the metadata of the fields:
🌐
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 Field is: private final char[] java.lang.String.value The Field is: private int java.lang.String.hash The Field is: private static final long java.lang.String.serialVersionUID The Field is: private static final java.io.ObjectStreamField[] java.lang.String.serialPersistentFields The Field is: public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER
🌐
Real's HowTo
rgagnon.com › javadetails › java-get-fields-and-values-from-an-object.html
Get fields and values from an Object - Real's Java How-to
public class Dummy { public String value1 = "foo"; public int value2 = 42; public Integer value3 = new Integer(43); private String value4 = "bar"; } We want to list the fields and the values of an instance. import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; public class ObjectUtils { private ObjectUtils() {} public static Map<String, Object> getFieldNamesAndValues(final Object obj, boolean publicOnly) throws IllegalArgumentException,IllegalAccessException { Class<? extends Object> c1 = obj.getClass(); Map<String, Object> map = new
Find elsewhere
🌐
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
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › class-getfields-method-in-java-with-examples
Class getFields() method in Java with Examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate getFields() method import java.util.*; class Main { private Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // ...
🌐
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
The following Java program to show you how to use the above ClassUtils class to get field names of an object. ... import java.util.List; public class FieldNamesExample1 { public static void main(String... args) { Customer customer = new Customer(); List<String> allFieldNames = ClassUtils.getAllFieldNames(customer.getClass()); allFieldNames.forEach(System.out::println); } } The output as below.
🌐
W3Schools Blog
w3schools.blog › home › java reflection get all public fields
Java reflection get all public fields
June 26, 2019 - The getFields() method is used to get the array of public fields of the Class. ... package com.w3spoint; public class Rectangle { private int defaultLength = 10; private int defaultWidth = 5; public String testField; public void drawShape(String color) { System.out.println("Rectangle create ...
🌐
Calazan
calazan.com › how-to-print-the-values-of-all-the-fields-of-an-object-in-java
How to print the values of all the fields of an object in Java | Calazan.com
August 17, 2011 - Blog / How to print the values of all the fields of an object in Java ... I was just doing some Java coding and I needed to check the values of a bunch of fields of an object (mostly numbers). Normally I’d just call and print each get() method if I just need to check a few fields, but the ...
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › reflect › object › get.html
Getting Field Values
Because the height is a primitive type (int), the object returned by the get method is a wrapper object (Integer). In the sample program, the name of the height field is known at compile time. However, in a development tool such as a GUI builder, the field name might not be known until runtime. To find out what fields belong to a class, you can use the techniques described in the section Identifying Class Fields. ... import java.lang.reflect.*; import java.awt.*; class SampleGet { public static void main(String[] args) { Rectangle r = new Rectangle(100, 325); printHeight(r); } static void prin
🌐
Together-java
together-java.github.io › ModernJava › reflection › get_all_fields.html
Get all Fields - Modern Java
To get a list of all fields, including private and package-private ones, you need to use getDeclaredFields. import java.lang.reflect.Field; class Main { void main() { Class<Soup> soupClass = Soup.class; IO.println("Using getFields"); Field[] publicFields = soupClass.getFields(); for (var field ...
🌐
TutorialsPoint
tutorialspoint.com › get-the-list-of-all-the-public-fields-in-java
Get the list of all the public fields in Java
June 25, 2020 - Also, the getFields() method returns a zero length array if the class or interface has no public fields that are accessible or if a primitive type, array class or void is represented in the Class object. A program that demonstrates this is given as follows − ... import java.lang.reflect.*; ...