0

I know what reflection does, but I want to know in what exact case that we can use it. Like, using reflection we can come to know whether the class contains the specified method or not. I also want to know the actual scenario where this kind of requirements can come in picture? and does the use of reflection have any impact on application performance?

Krypton
  • 3,337
  • 5
  • 32
  • 52
Kedar Parikh
  • 807
  • 1
  • 14
  • 19

2 Answers2

2

Performance of reflection is previously answered here Java Reflection Performance

However just to quickly summarise:

Quoting Java's documentation on reflection:

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Reflection can be useful in case that you cannot access some API directly (because the API is not exposed to the public) or you want to automate some thing (unit testing or something).

Community
  • 1
  • 1
Krypton
  • 3,337
  • 5
  • 32
  • 52
  • 1
    Reflection can be used to do all the dirty work (breaking Singleton, accessing private fields / methods, and lots more..) at the cost of overall system performance. – TheLostMind Sep 18 '14 at 07:26
  • 2
    A typical use case of Reflection is in Java Annotations: http://tutorials.jenkov.com/java-reflection/annotations.html – blagae Sep 18 '14 at 07:27
2

Today, many Java (enterprise) applications rely heavily on the use of annotations that can be processed at runtime. This is only possible using reflection. In fact, current Java EE standards are basically built around annotations which are evaluated by the Java EE application server at runtime. And this is also where performance aspects may be an issue: A heavily-loaded server handling millions of requests per day will have to do millions of reflective method calls, and milliseconds per invocation may count in those scenarios.

However, it is considered worth the overhead in terms of processing time (scales well too) compared to the increase in maintainability of source code and application systems.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
JimmyB
  • 12,101
  • 2
  • 28
  • 44