0

I grabbed this piece of code:

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

However I want something to that will grab the attributes from the live object rather than the Class. I know I need introspection I'm just not sure how to grab from the live object.

Community
  • 1
  • 1
Will
  • 8,246
  • 16
  • 60
  • 92

3 Answers3

1

This:

Object value = field.get(abc);

Grabs the value from the instanticated Object referenced by abc.

You can only introspect Classes, and then use the provided Fields and Methods to interact with instantiated Objects.

dngfng
  • 1,923
  • 17
  • 34
0

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

ClassABC abc = new ClassABC();

Above declaration you created object of class ClassABC.

Object value = field.get(abc);

field.get(abc) will return you value of field for object abc. This way you can do introspection on values of properties of Object at runtime.

#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.

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
0

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

The "live" object is an instance of some class, and that class will determine what fields the object has. The code in your question does exactly what you require.

(Java doesn't allow you to add new fields / attributes to an object on the fly ... like languages such as Javascript, Python, Ruby and so on.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216