How do I iterate over class members?

前端 未结 1 392
我在风中等你
我在风中等你 2020-12-04 19:19

I am using the Java version of the Google App Engine.

I would like to create a function that can receive as parameters many types of objects. I would like to print o

相关标签:
1条回答
  • 2020-12-04 19:56

    Yes, you do need reflection. It would go something like this:

    public static void getObject(Object obj) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            //field.setAccessible(true); // if you want to modify private fields
            System.out.println(field.getName()
                     + " - " + field.getType()
                     + " - " + field.get(obj));
        }
    }
    

    (As pointed out by ceving, the method should now be declared as void since it does not return anything, and as static since it does not use any instance variables or methods.)

    See the reflection tutorial for more.

    0 讨论(0)
提交回复
热议问题