this post was submitted on 15 Apr 2024
397 points (91.6% liked)
Programmer Humor
19512 readers
387 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
If you want to be able to eg. (de)serialize non-public fields of a type for any reason, you'll need some way to get around the access restriction. Mocking is another use case – although it's a philosophical discussion whether you should be mocking non-public fields.
And this isn't just a Java thing, the comment you're responding to has an example in C#, and you can do something similar in a lot of languages that support runtime reflection. Barring runtime reflection support you can do pointer math if the language supports it. Access restrictions on fields are there to stop casual misuse of private fields, but sometimes you actually may want to be able to step over those restrictions if you really know what you're doing.
Yea, what @hydroptic@sopuli.xyz posted is actually Java
If you're building in a backdoor anyways, why would the backdoor require 5 lines of weird reflection to get the type, type info, fieldinfo with the correct binding flags, and then invoking the method?
I think it's kinda neat compared to C#, just being able to say "Ignore private/protected/internal keywords"
Reflection is sometimes a necessary evil. At least it makes it harder to abuse the class and if you do, then you are responsible if something goes wrong.