How do you access protected Java method in thirdparty library?

Viewed 27590

Assume that you must access a protected method of a Java object that you receive somewhere in your code. What is your solution?

I know one approach: You can employ reflection and call setAccessible(true) on the Method object.

Any other idea?

8 Answers

If a class is not final, you can use an anonymous class to call its protected method:

new ClassWithProtectedMethod() {
    @Override
    protected void method() {
        super.method();
    }
}.method();

Note, making method() public is unnecessary (since the new anonymous class is in the same package).

Related