使用反射来了解字段和相对值

Using reflection to know fields and the relative values

我正在尝试使用反射来了解 Class (MyClass) 的字段和相对值。

到目前为止我已经这样做了,但这让我只知道字段和相关类型(字符串、整数等)而不是我的值:

    MyClass myClassFromDB = <--- I filled this object by making a query with hibernate
    Class <?> myClass= myClassFromDB.getClass();        
    Field [] fieldList= myClass.getDeclaredFields();        

    for(Field field: fieldList){            
            System.out.println(field.getName()+": "+myClass.getDeclaredField(field.getName()));             
    }

我以为使用 getDeclaredField() 我会得到这些字段的值,但我得到的只是这样 private java.lang.Integer package.className.FieldName

为了获得您需要像这样使用的字段值

for(Field field: fieldList){            
    try {

        // Will return field value of object type, you need to cast it to the required type. For identifying the object type you can use 'instanceof' keyword.            
        Object object = myClass.getDeclaredField(field.getName()).get(myClassFromDB);

        System.out.println("object :: "+object);

        if(object instanceof String){
            System.out.println("val :: "+(String)object);
        } // Similarily you can do it for other types.

    } catch (IllegalArgumentException ex) {
        System.out.println("IllegalArgumentException :: "+ex.getMessage());
    } catch (IllegalAccessException ex) {
        System.out.println("IllegalAccessException :: "+ex.getMessage());
    }
}

get(instance) -- 将return字段值与字段相关联。