反射 - 获取私有字段值

Reflection - getting private field value

我正在测试视图模型并想访问私有字段:

    val currentTrainingField = viewModel.javaClass.getDeclaredField("currentTraining")
    currentTrainingField.isAccessible = true
    val currentTraining = currentTrainingField.get(currentSetField)

我收到一个错误: 无法将 com.myapp.Training 字段 com.myapp.WorkoutExerciseViewModel.currentTraining 设置为 java.lang.reflect.Field

我该如何处理?

val currentTrainingField = viewModel.javaClass.getDeclaredField("currentTraining")
currentTrainingField.isAccessible = true


val currentTraining = currentTrainingField.get(viewModel)

您放宽了该字段的范围,但您应该访问特定对象上该字段的值,此处 viewModel