Loop over all fields in a Java class

前端 未结 4 1838
猫巷女王i
猫巷女王i 2020-11-28 09:38

I have a Java class that has a number of Fields.

I would like to Loop over al lthe fields and do something for the one\'s that are null.

For ex

4条回答
  •  不知归路
    2020-11-28 10:02

    Yes, with reflection.

    Use the Class object to access Field objects with the getFields() method.

    Field[] fields = ClassWithStuff.class.getFields();
    

    Then loop over the fields. This works because all fields you have declared are public. If they aren't, then use getDeclaredFields(), which accesses all Fields that are directly declared on the class, public or not.

提交回复
热议问题