How to fill all the fields in the class?

前端 未结 5 1645
时光说笑
时光说笑 2021-01-12 16:40

Suppose I have a class that has a lot of different fields. This class is a DTO and for testing purposes, I do not care about actual values, just it exists. Is there any tool

5条回答
  •  被撕碎了的回忆
    2021-01-12 17:18

    You can get the type of the field by reflection, and then initialize it to whatever you want, also using reflection.

    public static void main(String[] args) {
            MyDTO myDTO = new MyDTO();
            Field [] fields = myDTO.getClass().getDeclaredFields();
            for (Field field: fields){
                if (field.getType().equals(Integer.TYPE)){
                    //Primitives are already initialized to 0, so no need to do anything.
                }else if (field.getType().equals(String.class)){
                    System.out.println("String");
                    //Invoke setter method with reflection, initialize to ""
                }
            }
        }
    

提交回复
热议问题