https://www.programiz.com/java-programming/reflection
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. it’s a form of metaprogramming. It’s also a great source of confusion.
Reflection was created for a specific purpose, to discover the functionality of a class that was unknown at compile time, similar to what the dlopen and dlsym functions do in C. Any use outside of that should be *heavily *scrutinized.
Drawbacks of Reflection
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.
Security Restrictions
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
Performance Overhead
Reflection uses meta information about class,variables and methods this increase overhead, performance issue and security threat.
Why Reflection is slow?
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.
The JITted code for instantiating a class B is incredibly lightweight. Basically it needs to allocate enough memory (which is just incrementing a pointer unless a GC is required) and that’s about it - there’s no constructor code to call really; I don’t know whether the JIT skips it or not but either way there’s not a lot to do.
Compare that with everything that reflection has to do:
- The compiler can do no optimization whatsoever as it can have no real idea about what you are doing. This probably goes for the
JITas well - Everything being invoked/created has to be discovered (i.e. classes looked up by name, methods looked at for matches etc)
- Arguments need to be dressed up via boxing/unboxing, packing into arrays,
Exceptionswrapped inInvocationTargetExceptionsand re-thrown etc. - Check that there’s a parameterless constructor
- Check the accessibility of the parameterless constructor
- Check that the caller has access to use reflection at all
- Work out (at execution time) how much space needs to be allocated
- Call into the constructor code (because it won’t know beforehand that the constructor is empty)
https://stackoverflow.com/questions/1392351/java-reflection-why-is-it-so-slow/1392379#1392379