Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read object attribute dynamically in java?

Tags:

java

object

core

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.

like image 387
Mike Avatar asked Oct 12 '11 20:10

Mike


1 Answers

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.

like image 61
Vivin Paliath Avatar answered Oct 03 '22 01:10

Vivin Paliath