I have basic question. Java provides encapsulation to hide data from outside world and provide appropriate access using access modifiers. Then java introduced reflection which allows you to access everything available on class from anywhere. i am wondering why there is need to providing reflection.
-
Try implementing a Dependency Injection framework without reflection. – Marko Topolnik Oct 27 '16 at 09:47
-
Sometimes, in order to have a complete dynamic behavior, you need to invoke a method depending on the name for example. – Isukthar Oct 27 '16 at 09:47
-
maybe this wil help -> http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful – a-sir Oct 27 '16 at 09:48
-
Possible duplicate of [Dosen't Reflection API break the very purpose of Data encapsulation?](http://stackoverflow.com/questions/16635025/dosent-reflection-api-break-the-very-purpose-of-data-encapsulation) – ArcticLord Oct 27 '16 at 09:51
1 Answers
When speaking about encapsulation, you can think of Java Reflection API as an useful way to fine-tune visibility of class members beyond the keyword modifiers like "private" or "protected". Let's say you need restrict visibility of internal state to your business logic, but you need to provide access to that state to the dependency injection (DI) framework, ORM or some other generic infrastructure. There are three ways to do that:
- You expose public accessors, which will unnecessarily contaminate the business API (because they'll be usable by business logic too, which is not desirable)
- You implement a pattern like ActiveRecord, where an object knows how to store himself in database, serialize to XML or fetch dependencies.
- ORM and DI will use reflection to get information about internal state and prepare it for use by business logic.
The last approach is usually better, because it allows to keep your public API clean (not the case with first approach) and architecture loosely coupled (patterns like ActiveRecord violate single responsibility principle putting too many hats on the same object).
Moreover, access to private members via reflection is not absolute: it still can be protected. Java security mechanisms allow to block access to private members for unauthorized clients (have a look at the list of exceptions on Field::get and Method::invoke).

- 652
- 7
- 17