Covert Java: Hacking Non-Public Methods and Variables of a Class
"Anything can be made to work if you fiddle with it. If you fiddle with something long enough, you'll break it."
Murphy's Technology Laws
In this chapter
- The Problem of Encapsulation
- Accessing Packages and Protected Class Members
- Accessing Private Class Members
- Quick Quiz
- In Brief
The Problem of Encapsulation
Encapsulation is one of the pillars of object-oriented programming. The purpose of encapsulation is separation of the interface from implementation and modularity of application components. It is generally recommended that you make data members private or protected and provide public accessor and mutator functions (also known as getter and setter functions). It is also sometimes recommended that you make internal implementation methods private or public to protect a class from being used incorrectly. Following the principle of encapsulation helps create a better application, but occasionally it can prove to be an obstacle for usage that was not foreseen by the class developer.
We will use java.awt.BorderLayout in our experiments. Maybe at some point this will encourage JavaSoft engineers to add public methods. We will obtain the source code for BorderLayout from src.jar in the JDK installation directory.