Java ReflectionUtils gives us a way to make private variables accessible and modifiable. I just wrote some code which intercepts a process and modifies some private variables of an object.
How safe is this? My doubt is, What if in future, the person who owns this object decides to rename it to something else ? Since its a private var, he is completely entitled to.
If this is unsafe, then what is the point of ReflectionUtils allowing us to set private variables at all ?
Thanks in advance.
Like with any other thing in the world, if you really know what you're doing, and there's no better way, then it could be ok to do it. You just need to be prepared for the situation that this might stop working, so you need to prepare very well for this and really understand all the pros and cons. In the future someone will most likely need to somehow reimplement this functionality, so be clear that it is there, what's the purpose and how it works, what it should do and what it shouldn't. You can use automated tests for this. It is a bad practice, same like doing tracheotomy or chopping a limb of perfectly healthy person would be a crime, but when you do it to save the person life it isn't a crime, but legal operation, you might be even called hero for being brave and smart enough to do it. When there really wouldn't be better way, what would you do? Same applies here, that's life, just don't use it as an excuse to do bad things.
From my personal diary, I have worked on very big project which nulled some private fields via reflection. I wasn't that experienced back then and I didn't even have idea that such thing may be "implemented" there. I was searching three full days for it and I wasn't the only one who tried to find the cause of the problem, we didn't even understand what was exactly happening, as at first the problem was reported as just missing some values, but it appeared that there's much more of things that were wrong there. Short story long, it ate 3 days of my life searching for it, there were no tests for it, nor anything, just such a creepy hidden flower in the code. Was this proper implementation? For me it was as bad as it only could. Of course later I needed to understand why it is there and how to reimplement and fix it. That just wasn't nice. That's why I don't like to use reflection like this, And to be honest I even don't like annotations, to me they are just spells someone put on code. You can argue that it save time or something, that everyone knows them etc., but really you can do it much better with plain java, just you need to know more and think more. When your really know what these are doing you can really do it better than any framework, but that's very broad topic and especially for newcomers it is much easier to love the framework, just better it will not be a blind love.