How to use the Accessible Flag in Java

I have long held to the belief that Java’s reflection mechanism is one of it’s most powerful aspects. Sure many languages today have similar features, but to me Java still stands head and shoulders above the rest.

My first language was Java, I then went on to learn C/C++ and a host of other languages. The unfortunate part for me: I use reflection in my sleep. When working with GWT, I find reflection strongly influencing the way I write code, even though GWT doesn’t have it.

The one part of reflection I haven’t played with until recently was the Accessible Flag. It’s a little flag of each Field; Method and Constructor that allows you to suppress the accessibility checks (protected, package-protected and private). Sounds like an awful thing, doesn’t it. Well, in typical Java fashion: it’s protected by a Security check (to make sure the administrator has allowed your code to tamper in such ways). The Accessibility flag is in fact how the ObjectOutputStream and ObjectInputStream classes access your private fields for Serialization.

Take a look at the JavaDocs for AccessibleObject to see the various methods available to you. The only trick when using the Accessible flag is: it is only set for the Class that actually sets it, therefore: you must setAccessible from the same class that will invoke the methods that require the flag to be set.

  • If you have class A and class B
  • Class A invokes setAccessible(true) on a Field object and passes it to class B
  • Class A invokes doOperation() on class B
  • doOperation in class B invokes Field.set on the Field object passed be class A
  • Field.set will throw an IllegalAccessException

In order to make the structure above work, either class A must be the one to invoke Field.set, or class B must be the one to invoke setAccessible.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: