Java Annotations · interview question
Consider a custom annotation with RetentionPolicy.RUNTIME placed on a method. Why might method.invoke() be used alongside this annotation?
Multiple choiceHardchapter-16-curatedpremiumjava-annotationsretention-policies
Answer and explanation
Correct answer
C. To dynamically execute the method based on its annotation metadata.
Why
Using method.invoke() allows the framework to execute methods dynamically based on the presence and configuration of annotations. This is useful for tasks like configuring service endpoints or handling specific business logic.
Test yourself on Java Annotations
A free test with instant, explained results. No account needed.
More Java Annotations questions
- Given the following custom annotation, what is the default retention policy if none is specified?
- Why does the setAccessible(true) method in Java reflection matter in practice?
- How does breaking encapsulation using setAccessible(true) impact a Java application?
- Why do teams use Java annotations in production code?
- How would you explain a key limitation of compile-time annotation processing in a Java interview?
- Which Java Reflection method is used to access annotations at runtime?