There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

  • Java Tutorials: Reflection API / Advanced Language Topics: Reflection

Related questions

  • What is reflection, and why is it useful?
  • Java Reflection: Why is it so bad?
  • How could Reflection not lead to code smells?
  • Dumping a java object’s properties

Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

Answer from polygenelubricants on Stack Overflow
Top answer
1 of 7
116

There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

  • Java Tutorials: Reflection API / Advanced Language Topics: Reflection

Related questions

  • What is reflection, and why is it useful?
  • Java Reflection: Why is it so bad?
  • How could Reflection not lead to code smells?
  • Dumping a java object’s properties

Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

2 of 7
49

Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.

MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
    String propertyName = propertyDesc.getName();
    Object value = propertyDesc.getReadMethod().invoke(bean);
}
🌐
Boraji
boraji.com › how-to-iterate-properites-in-java
https://boraji.com/how-to-iterate-properites-in-java
March 1, 2017 - package com.boraji.tutorial; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; /** * @author imssbora */ public class IterateProperitesExample3 { public static void main(String[] args) { Properties props = new Properties(); props.setProperty("1", "One"); props.setProperty("2", "Two"); props.setProperty("3", "Three"); props.setProperty("4", "Four"); props.setProperty("5", "Five"); // Iterating properties using Entry Set Set<Entry<Object, Object>> entries = props.entrySet(); for (Entry<Object, Object> entry : entries) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } }
Discussions

Loop over all fields in a Java class - Stack Overflow
I have a Java class that has a number of Fields. I would like to Loop over al lthe fields and do something for the one's that are null. For example if my class is: public class ClassWithStuff {... More on stackoverflow.com
🌐 stackoverflow.com
June 14, 2013
reflection - How to iterate through all properties of a Java bean - Stack Overflow
Below is my bean structure. Employee.java is the parent bean. I would like to iterate through all the properties till the Zip.java and manipulate the values. I tried to iterate this using reflecti... More on stackoverflow.com
🌐 stackoverflow.com
June 5, 2015
Better way of going about looping through all fields in a class I'm writing?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
13
3
September 6, 2021
Java question: How to loop through Student object attributes and check which fields are null? import java.util.*; import java.lang.reflect.Field; //Student class class Student{ private String name = "x"; private int age; private int height; private String gender; private double grade; // main method public static void
Answer to Java question: How to loop through Student object More on chegg.com
🌐 chegg.com
1
October 8, 2021
🌐
Coderanch
coderanch.com › t › 441765 › java › Loop-list-objects-attribute
Loop through the list of objects to get attribute. (Beginning Java forum at Coderanch)
April 19, 2009 - How can i list through the list?? ... Well, you can use a for-each loop for this purpose like below: But this is not a good practice, because you can use Map classes instead of those List classes, so you can get the student quickly and in a smart-way without having a loop.
🌐
Coderanch
coderanch.com › t › 599586 › java › Properties-Class
for-each and Properties Class [Solved] (Beginning Java forum at Coderanch)
December 5, 2012 - I cannot seem to figure out the syntax of the for loop. I want the correct syntax to do something like: I guess I need to somehow convert the list of keys to an array or set? TIA. ... There is no "keys" http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#propertyNames() WP ... I meant keySet. Typo. However, I figured it out. ... Unfortunately, the Properties class was made to implement Map<Object, Object> when it clearly should have been Map<String, String>. This was probably because Properties was written long before generics came into the language, and Sun in their infinite wisdom chose to retroactively implement Map<Object, Object> in order to not break backwards compatibility for clients using their Properties in an incredibly stupid way.
🌐
Savecode
savecode.net › code › java › java+loop+through+object+properties
java loop through object properties - SaveCode.net
July 22, 2020 - import java.lang.reflect.*; public class DumpFields { public static void main(String[] args) { inspect(String.class); } static void inspect(Class klazz) { Field[] fields = klazz.getDeclaredFields(); System.out.printf("%d fields:%n", fields.length); for (Field field : fields) { System.out.printf("%s %s %s%n", Modifier.toString(field.getModifiers()), field.getType().getSimpleName(), f...
Find elsewhere
Top answer
1 of 5
1

getDeclaredFields()

for (Field field : yourObject.getClass().getDeclaredFields()) {
//do stuff
}
2 of 5
1

I strongly recommend to use an existing library and to avoid reflection in this case! Use JPA or Hibernate for database uses, use JAXB or similar for JSON/XML/other serialization, etc.

However, if you want to see what an example code would look like you can have a look at this:

package myOwnPackage;
import java.lang.reflect.Field;


class Address {
    private String addr1;
    private String addr2;
    private String city;
    private Zip zip;
}
class Contact {
    private String phone;
    private String email;
}
class Employee {
    private String id;
    private String name;
    private int age;
    private Address addr;
    private Contact cont;

    public void setAddr(Address addr) {
        this.addr = addr;
    }
}

class Zip {
    private String zipCd;
    private String zipExt;
}

public class Main {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {

        Employee employee = new Employee();
        employee.setAddr(new Address());

        printFields("", employee);
    }

    private static void printFields(String prefix, Object container) throws IllegalAccessException {

        Class<? extends Object> class1 = null; 
        Package package1 = null;

        if (container != null)
            class1 = container.getClass();

        if (class1 != null)
            package1 = class1.getPackage();

        if (package1 == null || !"myOwnPackage".equals(package1.getName())) {
            System.out.println(container);
            return;
        }

        for (Field field : class1.getDeclaredFields()) {
            System.out.print(prefix+field.getName()+": ");

            // make private fields accessible
            field.setAccessible(true);

            Object value = field.get(container);
            printFields(prefix+"  ", value);
        }
    }
}

Downsides of my code:

  • This code uses reflection, so you are limited at the depth of fields
  • Inherited fields are not printed
🌐
Reddit
reddit.com › r/javahelp › better way of going about looping through all fields in a class i'm writing?
r/javahelp on Reddit: Better way of going about looping through all fields in a class I'm writing?
September 6, 2021 -

I'm writing a program as an opportunity to learn more about java from the ground up. I've encountered some classes where they include a properties hashmap of all the fields in a class, which I've found useful when writing log messages (since I'm using Selenium, it'd be nice to use this general string in log messages, for instance:

public String toString(){
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(String.format("class %s's properties:",this.getClass())
        properties.keySet().forEach(property -> {
            stringBuilder.append(String.format(
            "\n%30s:%s",property,properties.get(property)));
        });
        return stringBuilder.toString();
}

I'm thinking the least invasive way of implementing this hashmap is to basically write a super getter? as opposed to storing all fields in said hashmap and making normal getters and setters go through the hashmap. ya? is there a better way to go about this altogether?

thanks for your input.

Top answer
1 of 2
4
In Java you can use Class.getMethods() which will return all public functions. Store that in an array and then iterate through it by checking if the function name contains “get”. Using reflection you can invoke the methods in that array and just mash up the data however you want. Edit: I will say though, if you need to do this you might be looking at a design issue. Like your loggers should just explicitly spit out what the function does and needs at that moment. So if I’m calling a REST API and I get a timeout, my logger should tell me what class, what function and what error happened. Not give me all the details of the class’ getters. All in all, you know what you want your code to do so go at it. I just like to keep my loggers relatively clean otherwise it gets crazy with big apps.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Coderanch
coderanch.com › t › 397254 › java › Property-File-Iteration
Property File Iteration (Beginning Java forum at Coderanch)
September 29, 2004 - I'm trying to get a list of the key/value pairs in a property file without using the java.util.Properities.list() method. This is what I have thus far:.
🌐
Mendix
community.mendix.com › link › space › java-actions › questions › 124497
Looping through the attributes in Java.
May 2, 2023 - The Mendix Forum is the place where you can connect with Makers like you, get answers to your questions and post ideas for our product managers.
🌐
Team Treehouse
teamtreehouse.com › library › javascript-objects-2 › use-for-in-to-loop-through-an-objects-properties
Use `for in` to Loop Through an Object's Properties (How To) | JavaScript Objects | Treehouse
If the object's name is student, then the for in loop will look like this. 0:47 · The variable key represents a property name inside the object. 0:52 · A different property name gets assigned to this variable each time through the loop.
Published   June 16, 2020
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-iterate-through-collection-objects-in-java
How to Iterate through Collection Objects in Java - GeeksforGeeks
import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Collection<String> gfg = new ArrayList<>(); // Adding elements gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // Iterating using enhanced for loop for (String name : gfg) { System.out.println("Name : " + name); } } } ... The Iterator interface provides controlled iteration and allows element removal during traversal. ... import java.util.*; class GFG { public static void main(String[] args) { // Declaring the LinkedList LinkedList<String> gfg = new LinkedList<>();
Published   January 9, 2026
🌐
GeeksforGeeks
geeksforgeeks.org › java › properties-foreachbiconsumer-method-in-java-with-examples
Properties forEach(BiConsumer) method in Java with Examples - GeeksforGeeks
July 11, 2025 - Properties 1: {Book=500, Mobile=5000, ... Program 2: To show NullPointerException ... // Java program to demonstrate // forEach(BiConsumer) method....
🌐
Progress
community-archive.progress.com › forums › 00019 › 59589.html
Loop properties from a class from a method in that class - OpenEdge Development - Forum - Progress Community Archive
September 20, 2019 - It appears the value of private properties can't be read using reflection, which is a strange design choice, since this is possible in Java or c#... ... USING Progress.Reflect.Flags FROM PROPATH. USING Progress.Reflect.Property FROM PROPATH. BLOCK-LEVEL ON ERROR UNDO, THROW. ... DEFINE PRIVATE PROPERTY PrivateProperty AS CHARACTER NO-UNDO INITIAL "Hello!" GET. SET. ... DEFINE VARIABLE Properties AS Property NO-UNDO EXTENT. Properties = GetClass():GetProperties(Flags:Private OR Flags:Instance OR Flags:DeclaredOnly). MESSAGE Properties[1]:Name SKIP Properties[1]:Get(THIS-OBJECT) VIEW-AS ALERT-BOX.
🌐
FavTutor
favtutor.com › blogs › java-array-of-objects
Array of Objects in Java (with Examples)
December 1, 2023 - Here, objectArray[0] retrieves the object reference stored at index 0, allowing operations or access to the properties and methods of the MyClass object. Iterating through an array of objects is commonly done using loops, like the enhanced for loop or traditional for loop, to access each element:
🌐
Tutorialspoint
tutorialspoint.com › java › java_foreach_loop.htm
Java - for each Loop
import java.util.Arrays; import ... name ); System.out.print(","); } } } ... In this example, we're showing the use of a foreach loop to print contents of an array of Student Object....
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Iterate Over All Properties, can someone explain the loop here?
October 18, 2021 - I understand the lesson difference between own property and prototype, but I don’t why we are using loop or how this loop works exactly. Please “dumb” it down and simplify it as much as possible. I have copied what I have seen from the example, and I got the right answer by modifying ...