How do you access protected Java method in thirdparty library?

salman.mirghasemi picture salman.mirghasemi · Jun 20, 2011 · Viewed 20.9k times · Source

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?

Answer

rsp picture rsp · Jun 20, 2011

As per the Java access modifiers, besides extending the object (which you can't if you receive the object) is to access it from an object in the same package as the object you received. So your option is to create a wrapper class in the same package which retrieves the attribute via the protected method for you.