Learner
Learner

Reputation: 21445

Understanding Java reflection drawbacks

I am trying to understand the drawbacks as mentioned in Java docs

Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager.

What are the runtime permissions that reflection needs? What is security manager in this context? Is this drawback specific to Applets only?

Exposure of Internals

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

How reflection can break abstraction? and how does it affect with upgrades of the platform.

Please help me in clarifying these. Thanks a lot.

Upvotes: 1

Views: 9524

Answers (3)

Srikanth P
Srikanth P

Reputation: 1516

A framework class called dependency container was used to analyzes the dependencies of a class. With this analysis, it was able to create an instance of the class and inject the objects into the defined dependencies via Java Reflections. This eliminated the hard dependencies. That way the class could be tested in isolation, ex. by using mock objects. This was Dagger 1.

Main disadvantages of this process were two folds. First, the Reflection is slowing itself and second, it used to perform dependency resolution at runtime, leading to unexpected crashes.

Upvotes: 0

amitguptageek
amitguptageek

Reputation: 537

First you should always ask to yourself why reflection in your code. Aren't you able to do the operations without reflection. If YES then only you should use reflection. Reflection uses meta information about class,variables and methods this increase overhead, performance issue and security threat.

To understand the drawback of reflection in detail visit http://modernpathshala.com/Forum/Thread/Interview/310/what-are-the-drawbacks-of-reflection

Upvotes: 1

keshlam
keshlam

Reputation: 8058

Security "sandboxes" aren't limited to applets. Many other environments which permit less-than-completely-trusted "plug-in" code -- webservers, IDEs, and so on -- limit what the plug-ins can do to protect themselves from errors in the plug-in (not to mention deliberately malicious code).

Upvotes: 0

Related Questions