使用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的值,并輸出到控制臺上。