Using reflection in Java is very expensive because it affects performance very badly right.But I wonder that , reflection is widely used in container configurations (web.xml),frame works like Structs,REST.. , and ORM like hibernate etc. How it can be justified?Is it because reflection used only once when container is up or some other reason behind it?
-
It's justified essentially because there's not really an alternative to it for those sorts of frameworks. – JonK Oct 19 '15 at 14:54
-
1I think this will answer some of your concerts also: http://programmers.stackexchange.com/a/123959 – Damien O'Reilly Oct 19 '15 at 14:55
-
*"because it affects performance very badly right"*-- not right. There was a time when reflection in Java was very slow, now it doesn't. – Alex Salauyou Oct 19 '15 at 15:11
2 Answers
First, I wouldn't say that using reflection has such a detrimental effect on code performance. Of course, there is an overhead, but there are optimisation techniques in place, that make sure that the performance impact is kept to a minimum. As far as the trade - off between performance and usability is concerned, the specific requirements of the product being developer should be taken into account. For example, would I use a heavy reflection - based framework on mobile - I think not. Does it makes sense on the backend - I would say yes.
Second, having annotation based configuration doesn't always mean that there is reflection used at application runtime. There are frameworks that make use of the AnnotationProcessor
framework and generate java code during compilation, which is later used as "normal code". Also, a lot of frameworks use annotation configuration in conjunction with byte - code generation at runtime, so basically, reflection is kept at a minimum.

- 7,624
- 3
- 20
- 28
- There is no other way for them to do what they do (a good example of this might be Spring framework - it doesn't force you to use any interface when using dependency injection, and since it has no interface to use and doesn't know your classes at compile time, the only way is to inspect them via reflection)
- The reflection-heavy parts are not (should not) be executed too often
- Reflection isn't that very expensive if done right (e.g. if you only lookup the method you want to call once and then cache the
java.lang.reflect.Method
object found and use it in further invocations)

- 12,211
- 5
- 29
- 43