有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对打印对象属性的内省

我抓取了这段代码:

ClassABC abc = new ClassABC();
for (Field field : abc.getClass().getDeclaredFields()) {
    field.setAccessible(true);
    String name = field.getName();
    Object value = field.get(abc);
    System.out.printf("Field name: %s, Field value: %s%n", name, value);
}

from this question

然而,我希望能够从活动对象而不是类中获取属性。我知道我需要反省我只是不知道如何从活的物体上抓取


共 (3) 个答案

  1. # 1 楼答案

    However I want something to that will grab the attributes from the live object rather than the Class.

    “活动”对象是某个类的实例,该类将确定该对象具有哪些字段。你问题中的代码正符合你的要求

    (Java不允许您动态地向对象添加新字段/属性……比如Javascript、Python、Ruby等语言。)

  2. # 2 楼答案

    这是:

    Object value = field.get(abc);
    

    从abc引用的实例化对象中获取值

    您只能内省类,然后使用提供的字段和方法与实例化的对象进行交互

  3. # 3 楼答案

    Class has attributes/properties, Object is a state and it has only values for those attributes.

    ClassABC abc = new ClassABC();
    

    在上面的声明中,您创建了类ClassABC的对象

    Object value = field.get(abc);
    

    field.get(abc)将返回对象abc的字段值。通过这种方式,您可以在运行时对对象属性的值进行内省

    #Field.get()

    Returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.