YOUR FEEDBACK
The 4 Core Principles of Agile Programming
Siegfried wrote: Actually, every elephant has two left feet, and two right...


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


Private Conversations in Public

Digg This!

One of the principles of any OO language such as Java is an object's ability to encapsulate its data and provide clients with a specific and well-defined API. This is done through the visibility keywords public, protected, and private. The use of these is one of the first things any Java programmer learns; the fairly well-understood key points being that a public accessor (be it a method or a field) is visible to any other object, protected only to subclasses and private to no one but the class itself.

A not-uncommon scenario, however, is that when you're using a class, you find a gem of a method you want to call that's been marked as private, or you want to access or modify a field that isn't visible to your class. I find this occurs quite a bit with frameworks where you might be extending or calling someone else's code and it works fairly well except for one little twist that you need to complete your task. There is a way (that I describe below) that allows you to access private methods and fields and it's a useful technique that, in these situations, enables you to code your way out of a blind alley.

The secret lies in the java.lang.reflect package that lets you execute Java code reflectively. Typically this is used for such tasks as looking up a field, method, or constructor by name and then accessing it for a given object. It's very useful if your program has to consume objects at runtime that it has no prior knowledge of at compile time (like introspection, for example). The three classes - java.lang.reflect.Method, Field, and Constructor - however, all inherit from the java.lang.AccesibleObject. This has the method setAccessible(boolean) whose method comment is:


   * Set the "accessible" flag for this object to
   * the indicated boolean value. A value of "true" indicates that
   * the reflected object should suppress Java language access
   * checking when it is used. A value of "false" indicates
   * that the reflected object should enforce Java language access checks.

To best way to illustrate this is to take class A, which has a private method isFooBar();


public class A{
  private boolean fooBar;
  private boolean isFooBar(){
   return fooBar;
  }
}

Using reflection we can get the method and execute it as follows:


A object = new A();
Method fooBarMethod = A.class.getDeclaredMethod("isFooBar");
fooBarMethod.setAccessible(true);
try{
 System.out.println("FooBar=" + fooBarMethod.invoke(object);
} catch (Exception exc){
}

The key is the setAccessible(true) statement. If this weren't present, a java.lang.IllegalAccessException would be thrown. With the accessible set to true the code to execute the method and get the result can be in any class in the JVM. In addition to calling private methods, we can also set field values; the following code sets it to false:


Field fooBarField = A.class.getDeclaredField("fooBar");
fooBarField.setAccessible(true);
try{
 fooBarField.set(object,Boolean.FALSE);
} catch (Exception exc){
}

We're using the method setAc-cessible(boolean) as it was designed to allow reflection to ignore any visibility constraints; however, the setAccessible(boolean) method does go through the security manager, which throws a SecurityException if this kind of private invocation is now allowed. The default JRE security manager does not prohibit the accessibility being overridden, and if you wanted to check your JVM to see whether or not this technique was going to work, the code would be:


try{
 System.getSecurityManager().checkPermission(new ReflectPermission(""));
} catch (SecurityPermission exc){
 // VM not going to let you do funky reflection
}

I don't recommend using reflection and accessibility as a matter of normal programming, but when you're in a tight spot with a deadline breathing down your neck and you can see the API you need but it's just not there, it can be a lifesaver. You'll be linking to private field names and methods though so the next version of the framework or class library you're abusing might very well change and break your code. You won't pick up this breaking change at compile time because it's reflective and will only die at runtime.

It's very interesting that this month we have a great article on Java 2D and gaming, and last month we published a fantastic piece on Java3D using Mars rover images as examples. I hope this is a renaissance in both frameworks and we see more interesting uses in which Java apps can find their way onto the desktop.

About Joe Winchester
Joe Winchester, JDJ's Desktop Technologies Editor, is a software developer working on development tools for IBM in Hursley, UK.

LATEST JAVA STORIES & POSTS
Case Study: Java and the Mac
This is the story of a Mac application developer (okay - it's about two of them) who set out on a quest to find an application development tool based on Java so his boss would let him develop on the Mac platform, which he loved. There was only one catch - he had to find a tool th
A Lightweight Approach to SOA and BPM in Java Using jBPM
SOA is mostly associated with technologies such as BPEL, SCA and Web Services. But does SOA really imply these technologies? In this session we will show how you can use the service oriented approach while staying inside the Java world. jBPM is a powerful lightweight framework th
JavaOne 2008: Uncommon Java Bugs
Any large Java source base can have insidious and subtle bugs. Every experienced Java programmer knows that finding and fixing these bugs can be difficult and costly. Fortunately, there are a large number of free open source Java tools available that can be used to find and fix d
The 4 Core Principles of Agile Programming
One of the things I really enjoy at the moment is the recognition and adoption of agile programming as a fully fledged powerful way to deliver quality software projects. As its figurehead is a group of very talented individuals who have created the agile manifesto (http://agilema
JavaOne 2008: Sun Adds Comprehensive Video Capabilities to JavaFX
Sun Microsystems announced it has entered into a multi-year agreement with On2 Technologies to add comprehensive video capabilities, using On2 Technologies TrueMotion video codecs, to Sun's JavaFX, a family of products for creating Rich Internet Applications (RIAs) with immersive
JavaOne Archives - Dvorak Comments on AMD Intel Lawsuit on SYS-CON.TV
Conference in San Francisco. Dvorak held forth on a number of topics, including the new AMD/Intel lawsuit, the viability of Java and Sun, the value of (or lack thereof) of corporate PR, and whether or not a new book about Silicon Valley is really worth reading.
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING JAVA NEWS
KongZhong Corporation Reports Unaudited First Quarter 2008 Financial Results
KongZhong Corporation , a leading wireless value-added services (WVAS) and wireless media co