Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to loop through a classes members in java?

Tags:

java

dto

I have a DTO that has a whole bunch of members. I was wondering if Java supports the idea of a for(in) for the class. I don't think it does, but it would save me a ton of grief if it did, so, I figured I'd toss the question out there.

like image 575
Yevgeny Simkin Avatar asked Oct 30 '09 21:10

Yevgeny Simkin


People also ask

Can you loop through a list in Java?

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.

Can you loop through a Set in Java?

Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using the Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of the Set interface.

Can you loop through characters in a string Java?

Example 1: Loop through each character of a string using for loop. Characters in Programiz are: P, r, o, g, r, a, m, i, z, In the above example, we have used the for-loop to access each element of the string. Here, we have used the charAt() method to access each character of the string.

Is it possible to iterate through a Set?

There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variations.


1 Answers

Well, you can do it with reflection:

for (Field field : clazz.getFields())
{
    ...
}

(Or the equivalent for methods etc.)

You can then get the field values for a specific instance, or static values.

like image 54
Jon Skeet Avatar answered Oct 26 '22 06:10

Jon Skeet