how to read object attribute dynamically in java?

后端 未结 5 1188
清歌不尽
清歌不尽 2021-02-07 12:38

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;
           


        
5条回答
  •  一整个雨季
    2021-02-07 12:49

    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.

提交回复
热议问题