Carlsbad Cubes Wolf Paulus

java

How private are private fields after all?
By Wolf Paulus <wolf@wolfpaulus.com>

Posted Tuesday, June 14th, 2005

Last week, I sent the following brain teaser:

Can you write a void hack(Object obj) method that would change foo's private member variable, so that the output looked like this?

Psst: 74

A sharp developer came up with this solution:


Now there you have it. Just because a member is declared private doesn't mean it cannot be changed from outside.


Not only to emphasize this but also because it was more convenient, up to now, Swixml was only able to map public members.

FYI:
Swixml is a small GUI generating engine for Java applications and applets. Graphical User Interfaces are described in XML documents that are parsed at runtime and rendered into javax.swing objects.

While parsing an XML layout descriptor, the SwingEngine instantiates all the Components and assembles the GUI tree. In case a tag was given an id attribute, the SwingEngine will also put a reference to the instantiated object into an idmap. After all this is done, the SwingEngine introspect the class of a provided client object, e.g.

new SwingEngine( this ).render( ''xml/helloworld.xml'' ).setVisible ( true );

.. here ''this'' points to the client object.


If during this introspection member variables in the client's class are found, whose names match those in the idmap, the SwingEngine maps the reference into the member variable.


This used to work only with public members. Since this Swixml 1.5 however, the updated mapping considers ALL member variables in the whole class structure. This means even members in a super class and its super class ... are considered. BUT, to work consistent with serialization, members flagged as transient are not mapped automatically.

Mapping works recursively on a client object's class tree like this:




Disclosure: This blog is written and edited by me, it contains my words and my opinions only, and does not contain any content which might present a conflict of interest.
I am not compensated to provide opinion on products, services, websites and various other topics. This blog does not accept any form of cash advertising, sponsorship, or paid topic insertions. However, I will and do accept and keep free products, services, and other forms of compensation from companies and organizations. All advertising is in the form of advertisements generated by a third party ad network and identified as such.
I will only endorse products or services that I believe, based on my expertise, are worthy of such endorsement. Any product claim, statistic, quote or other representation about a product or service should be verified with the manufacturer or provider.

Published on: Tuesday, June 14th, 2005  •  Category: [java]

Article URL : http://wolfpaulus.com/journal/java/privatemembers.html