Java - 对象输入法(遍历输入变量)?

Java - object input method (iteratre through input variables)?

我正在尝试编写此方法,它需要传递一个对象,我想遍历变量,存储有关它的信息并访问值。

我想以这种方式访问​​它的原因是根据对象构造函数获得不同的输入,并通过字符串或文件将输出修改为其他用途。

如果有人因为我被难住了而有想法,请在 VVVV 下面的 for 循环中

public static String JsonCompiler(Object inputObject){
        String objectOutput="";

        Random random = new Random();
        int variation = (int) Math.floor(Math.random() * (3 - 1) + 1);

        System.out.println(variation);

       if(variation == 1){

           Field[] fields = inputObject.getClass().getDeclaredFields();

           for(Field field: fields) {

               System.out.println(field);
               //System.out.println(field + " - " + inputObject[field].toString);
               // variable 1 = inputObject.get{Employee.id} <<^^ somehow get to understand

           }

       }
       else if (variation == 2){

        }
       else {

       }
        return objectOutput;
    }

因此,对于字段,您必须首先确保它们是 public,您可以使用 field.canAccess(object) 进行检查。如果你想要字段中的值,你需要从对象中调用字段,例如 System.out.println(field.get(object)); 这感觉很尴尬,但字段只是 class 中的变量名,它是保存值的对象.

从那里您也可以通过使用 field.set(object, newValue) 确保类型相同来设置值,否则它会向您抛出异常。