Java reflection compilation example code#
They just make it less painful.Ĭonsidering Reflection is ok, if your code needs to be run occasionally. Even if you consider that modern VMs are much better in minimising the problem, they don’t mitigate it. There is always some performance overhead if you use reflection.
In terms of the performance: reflection usages can range from slightly-costly to holy-crap-what-is-happening-with-my-device-costly. Compilation will succeed, without any issues. The worst thing about that is, that you won’t know that your code will fail, until it gets to the part that is using Reflection in runtime. The internal code can be changed between versions. If you depend on something that was meant to be used only internally in the library, you can fry your code simply by updating to the newer release.
The author of the library can change what is not “exposed to the world” at any time and does not have to signal it. If something is not a part of public API, it can be changed at any time. This derives directly from the previous point, but has a different reasoning. Anything outside public API is off-limits. It might seem that your “violation” of the public api contract has no negative impact, but you might be wrong simply because you might not understand the library thoroughly enough. The “violation” of the public API contract can have negative impact on other parts of the code that you might not be aware of. It is possible that the unaccessible code is working correctly only under particular set of conditions. There are reasons behind particular architectural decisions. If the creator of the library wanted you to change a field or to override a method he/she wouldn’t add a final modifier. Those are the things that shouldn’t be modified using reflection. private, protected or package-private (no modifier) - limited access.final keyword - finalised fields, methods or classes.Especially if it’s a part of a released API. If you’re using a piece of code from another developer, you’re getting the code the way this developer intended it to be.
This is the most important rule of them all. Do not use Reflection to violate limitations set by other developers.