Search code examples
javaencapsulationuglifier

point of java encapsulation


I'm trying to figure why people say this is a good way to prevent access to your class file that you don't want but can't I just use reflection to access the class? Isn't obfuscation to prevent unauthorized access better because no one knows what your code does even if they use reflection?


Solution

  • The point of encapsulation is to prevent access to your implementation internal classes for the sake of cleaner code, not to technically prevent users of your class from accessing instances using reflection, or decompiling it.

    For example, if you have an HTTP client, you should encapsulate the streams and buffers you use, and only expose the request and response to the actual user of your class. This is designed so your--and their--code is cleaner, not so that they can never reflect on your class. Additionally, since the only API users are accessing is the external API, you are free to change the internals of your classes or code as much as you wish.