how to read object attribute dynamically in java?

Mike picture Mike · Oct 12, 2011 · Viewed 51.1k times · Source

Is there any way to read and print the object attribute dynamically(Java) ? for example if I have following object

public class A{
  int age ;
  String name;
  float income;

}

public class B{
 int age;
 String name;
}

public class mainA{
   A obj1 = new A();
   method(A);
   method(B); 
}

the output should be like

While running method(A):
Attribute of Object are age,name,income;
While executing method(B):
Attribute of Objects are age,name;

My question is I can pass various object in method(), is there any way I can access the attribute of the differnt object in general.

Answer

Vivin Paliath picture Vivin Paliath · Oct 12, 2011

You want to use The Reflection API. Specifically, take a look at discovering class members.

You could do something like the following:

public void showFields(Object o) {
   Class<?> clazz = o.getClass();

   for(Field field : clazz.getDeclaredFields()) {
       //you can also use .toGenericString() instead of .getName(). This will
       //give you the type information as well.

       System.out.println(field.getName());
   }
}

I just wanted to add a cautionary note that you normally don't need to do anything like this and for most things you probably shouldn't. Reflection can make the code hard to maintain and read. Of course there are specific cases when you would want to use Reflection, but those relatively rare.