manocha_ak
manocha_ak

Reputation: 902

Accessing non-public methods through patterns

Which pattern can be used, or what is the way, if I have some classes where some of the interface are protected, but I want to use it outside the package and out of the hierarchy?
I don't want to change the access modifier of those old (legacy) classes.

Upvotes: 0

Views: 115

Answers (5)

Andrew Spencer
Andrew Spencer

Reputation: 16474

Faster than reflection, but equally dirty (or possibly more so): define a class in the same package as the legacy classes. Give it all the public methods you want. Have these public methods delegate to protected methods of the legacy classes.

I think I need to wash my hands after typing that.

Upvotes: 0

If the part of the classes that you need access to is protected, you can access it via inheritance.
You may also be able to access the protected parts via those classes that do have access to the protected code.

A design pattern that can probably be used is Proxy. In this case, the Proxy could inherit from the class you're interested in, and make the methods you're interested in available locally.

Before all this, however, consider carefully why these parts of the interface did not have public scope. There may have been good reasons not to expose them.

Upvotes: 1

seahorse
seahorse

Reputation: 2470

You can use a class Adapter. The Class adapter will derive from the Legacy classes and expose public interface methods which will internally call your protected methods. Your client will call the public methods of the class adapter which will internally call your legacy classes.

Upvotes: 0

belgther
belgther

Reputation: 2534

The following code shows how to access such a field:

Field privateStringField = PrivateObject.class.
        getDeclaredField("privateString");

privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);

The same thing could be done in a method as well. But as a pattern, you better pack it in a static utility method such as ReflectionAccessor.accessField(Class class, Object object, String fieldName).

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691625

The whole point of a protected method is to make it inaccessible from the outside, and making methods protected is often some important point of a design pattern.

You want to break the encapsulation of the classes, and there is no design pattern that will help you do that. Only dirty reflection calls.

Upvotes: 0

Related Questions