Reflection API · interview question
Given a class 'Product' with a private field 'price', how can you dynamically change its value using reflection?
Multiple choiceMediumchapter-16-curatedpremiumreflection-apibreaking-encapsulation
Answer and explanation
Correct answer
A. Use getDeclaredField and setAccessible(true) before setting the value
Why
To change the value of a private field using reflection, you must first retrieve the Field object using getDeclaredField, call setAccessible(true) to bypass access checks, and then set the value.
Test yourself on Reflection API
A free test with instant, explained results. No account needed.
More Reflection API questions
- Given using Class.forName("com.example.MyClass") in Java, what outcome should you expect?
- Which method would you use to check if a class is an interface using Reflection?
- In what scenario would you prefer reflection for method invocation over direct method calls?
- Which of the following is NOT a drawback of using Java Reflection?
- If you use Method.invoke() to call a private method, what must you do first?
- How does Java's reflection API impact type safety?