Since you are using JPA, have you tried the JPA 2 metamodel (javax.persistence.metamodel). This will give you information about your JPA entities from the JPA metadata:

entityManager.getMetamodel().entity(entityClass). getAttributes();
Answer from bdoughan on Stack Overflow
Discussions

java - How do I iterate over class members? - Stack Overflow
I am using the Java version of the Google App Engine. I would like to create a function that can receive as parameters many types of objects. I would like to print out the member variables of the ... More on stackoverflow.com
🌐 stackoverflow.com
java - iterate over POJO properties and set it to another object - Stack Overflow
In our application I have a routine that manually iterates over the properties of an POJO loaded by Hibernate and assigns those properties to a new instance of that object and then saves it. e.g ... More on stackoverflow.com
🌐 stackoverflow.com
reflection - Loop over object setters java - Stack Overflow
It doesn't get better. Even POJOs should follow SOLID principles. Having 30 fields in one class ... is a smell by itself already. ... "Iterating over methods" seems pretty much of a wrong idea in OO programming. More on stackoverflow.com
🌐 stackoverflow.com
August 14, 2017
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
🌐
Coderanch
coderanch.com › t › 385565 › java › Parsing-List-Pojos
Parsing a List of Pojos (Java in General forum at Coderanch)
June 3, 2008 - I am stumped as it is a list of pojos. Any ideas will be much appreciated! Thanks in advance. [ June 03, 2008: Message edited by: Meghna Bhardwaj ] ... I think you will have to go through the List with an iterator or for-each and check whether the String is equal.
🌐
CodingTechRoom
codingtechroom.com › question › -iterate-pojo-properties-java
How to Iterate Over Properties of a POJO in Java? - CodingTechRoom
public class MyClass { private String name; private int age; public MyClass(String name, int age) { this.name = name; this.age = age; } // Getters public String getName() { return name; } public int getAge() { return age; } } Iterating over the properties of a POJO (Plain Old Java Object) allows you to access its fields programmatically.
Top answer
1 of 3
4

Here is an simple example to call setters via reflection (which needs to be adjusted):

[if this is a good approach, is another question. But to answer your question:]

public static void main(String[] args) throws Exception
{
    //this is only to demonstrate java reflection:
    Method[] publicMethods = TestPojo.class.getMethods(); //get all public methods
    TestPojo testObj = TestPojo.class.newInstance(); //when you have a default ctor (otherwise get constructors here)
    for (Method aMethod : publicMethods) //iterate over methods
    {
        //check name and parameter-count (mabye needs some more checks...paramter types can also be checked...)
        if (aMethod.getName().startsWith("set") && aMethod.getParameterCount() == 1)
        {
            Object[] parms = new Object[]{"test"}; //only one parm (can be multiple params)
            aMethod.invoke(testObj, parms); //call setter-method here
        }
    }
}

You can also save all setter-methods in an list/set for later re-use...
But as others already said, you have to be careful by doing so (using reflection)!

Cheers!

2 of 3
3

You can't easily - and you shouldn't.

You see, your POJO class offers some setters. All of them have a distinct meaning. Your first mistake is that all of these fields are strings in your model:

  • gender is not a string. It would rather be an enum.
  • "number" is not a string. It should rather be int/long/double (whatever the idea behind that property is)

In other words: you premise that "input" data is represented as array/list is already flawed.

The code you have written provides almost no helpful abstractions. So - instead of worrying how to call these setter methods in some loop context - you should rather step back and improve your model.

And hint: if this is really about populating POJO objects from string input - then get your string into JSON format, and use tools such as gson or jackson to do that (reflection based) mapping for you.

🌐
Coderanch
coderanch.com › t › 456909 › java › Looping-methods-reflection
Looping though get methods without using reflection (Java in General forum at Coderanch)
August 3, 2009 - True (and reflection sucks to debug/maintain), but the implementation is pretty straightforward. One thing you could do is implement a toHashMap() method which builds a HashMap of the current object. Downside of that is that you'd have to implement it in every class you want that functionality ...
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
🌐
Blogger
javarevisited.blogspot.com › 2022 › 12 › how-to-iterate-over-jsonobject-in-java.html
How to iterate over JSONObject in Java to print all key values? Example Tutorial
I have omitted constructor, getter and setter, and essential methods like equals(), hashcode(), and toString() for brevity but you must remember to include a no-argument constructor while creating POJO classes in Java, json-simple might not need that but other JSON parsing library like Jackson and Gson definitely need that. Anyway, Here is my sample Java program to demonstrate how you can loop over a JSONObject to print all properties and their values. public static void main(String args[]){ // Iterating over JSONOjbect to print all keys and values JSONParser parser = new JSONParser(); try { J
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-iterate-through-collection-objects-in-java
How to Iterate through Collection Objects in Java - GeeksforGeeks
The enhanced for loop is the simplest and most readable way to iterate through a collection. ... import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Collection<String> gfg = new ArrayList<>(); ...
Published   January 9, 2026
🌐
DigitalOcean
digitalocean.com › community › tutorials › iterator-design-pattern-java
Iterator Design Pattern in Java | DigitalOcean
August 4, 2022 - Same approach is followed by collection classes also and all of them have inner class implementation of Iterator interface. Let’s write a simple iterator pattern test program to use our collection and iterator to traverse through the collection of channels. IteratorPatternTest.java
🌐
Stack Overflow
stackoverflow.com › questions › 44892719 › iterate-through-the-parameters-for-a-method
java - Iterate through the parameters for a method - Stack Overflow
I know I can use an Array but I ... do this than Array ... You should use an array instead. ... Put your variables in an array an then iterate over the indices....
🌐
TechVidvan
techvidvan.com › tutorials › java-pojo-class
Java POJO class - Plain Old Java Object - TechVidvan
June 8, 2020 - POJO stands for Plain Old Java Object, which is used to increase the reusability and readability of the Java program. We will discuss how to use Java POJO Class and why it is important to learn it.
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);
}
🌐
Qlik Community
community.qlik.com › t5 › Design-and-Development › Pushing-a-Java-list-of-POJOs-from-global-variables-to-a-file › td-p › 2298536
Pushing a Java list of POJOs from global variables to a file
January 5, 2018 - Lets also assume this class has methods for returning name and age (getName() and getAge()). Lets also assume that your POJO instantiation is called myPojo and has been added to the globalMap using the below code.... ... In your tMap (or other component where Java can be used), you can use the following code to retrieve the values from the POJO's methods.....
🌐
Studytonight
studytonight.com › java-examples › java-pojo-class
Java POJO Class - Studytonight
This tutorial explains the concept of POJO or plain old Java objects. It also explains Java Bean classes.