Loop over all fields in a Java class

前端 未结 4 1837
猫巷女王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 09:57

    What are looking for is called reflection. Reflection lets you look at your own class, or another class to see what it is made of. Java has reflection built in, so you can use it right away. Then you can do stuff like -

    for(Field f : ClasWithStuff.getFields()){
        System.out.println(f.getName());//or do other stuff with it
    }
    

    You can also use this to get methods, constructors, etc, to do similar and cooler stuff.

提交回复
热议问题