RCH
RCH

Reputation: 1309

Reflection - getting private field value

I am testing viewmodel and would like to access private field:

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

I receive an error: Can not set com.myapp.Training field com.myapp.WorkoutExerciseViewModel.currentTraining to java.lang.reflect.Field

How should I handle that?

Upvotes: 2

Views: 1720

Answers (1)

ocos
ocos

Reputation: 2244

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


val currentTraining = currentTrainingField.get(viewModel)

You relaxed the field's scope but you should access the value of that field on a specfic object, here viewModel.

Upvotes: 6

Related Questions