• hydroptic@sopuli.xyz
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    3 months ago

    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.