Skip to content
Sharp

Reflection API · interview question

In which scenario would you need to use setAccessible(true) before calling Method.invoke()?

Multiple choiceMediumchapter-16-curatedpremiumreflection-apimethod-invoke
java
Method privateMethod = clazz.getDeclaredMethod("privateMethodName");
privateMethod.setAccessible(true);
Choose one answer
Answer and explanation

Correct answer

C. To access a private method.

Why

setAccessible(true) is used to bypass Java's access control checks, allowing reflection to invoke private or protected methods.

Test yourself on Reflection API

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

Start free test
All Reflection API questions →