使用Java反射获取对象属性值的步骤如下:
Class<?> clazz = object.getClass();
Field field = clazz.getDeclaredField("fieldName");
field.setAccessible(true);
Object value = field.get(object);
完整的示例代码如下:
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
MyClass myObject = new MyClass();
myObject.setField("Hello World");
Class<?> clazz = myObject.getClass();
Field field = clazz.getDeclaredField("field");
field.setAccessible(true);
Object value = field.get(myObject);
System.out.println(value);
}
static class MyClass {
private String field;
public void setField(String field) {
this.field = field;
}
}
}
上述示例代码中,通过反射获取了私有属性field的值,并输出到控制台上。