0

I have an Object1(pojo class) with 4 keys and another Object2 has 7 keys now i wanna read each value in List in loop as well as List<Object2>

Is there any utilities Available for this kind of iterations

Thanks in advance....

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Manikanta Reddy
  • 849
  • 9
  • 23

1 Answers1

2

You'll need to use reflection.

import java.lang.reflect.*;

class MyObject {
  String x = "hello";
  int y = 42;
  String z = "world";
}

public class Test {
  public static void main(String[] args) throws Exception {
    MyObject obj = new MyObject();
    for (Field f : obj.getClass().getDeclaredFields()) {
      System.out.println(f.getName() + ": " + f.get(obj));
    }
  }
}

Prints:

x: hello
y: 42
z: world

Now, that works, but reflection is generally a lot slower than just accessing the fields. So, unless you need your code to be generic and work on arbitrary objects, you're better off accessing the fields by hand.

Vlad
  • 18,195
  • 4
  • 41
  • 71