Skip to content
Sharp

Reflection API · interview question

Which of the following is a correct way to access a private field 'id' of an object using Reflection?

Multiple choiceMediumchapter-16-curatedpremiumreflection-apibreaking-encapsulation
java
Field field = obj.getClass().getDeclaredField("id");
Choose one answer
Answer and explanation

Correct answer

C. Field.setAccessible(true);

Why

To access a private field using Reflection, you must first call 'setAccessible(true)' on the Field object. This overrides the field's Java access control allowing modification.

Test yourself on Reflection API

A free test with instant, explained results. No account needed.

Start free test
All Reflection API questions →