Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..

2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
In many cases, the end of the year gives you time to step back and take stock of the last 12 months. This is when many of us take a hard look at what worked and what did not, complete performance reviews, and formulate plans for the coming year. For me, it is all of those things plus a time when I u...
SYS-CON.TV
Private Conversations in Public
Private Conversations in Public

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, Editor-in-Chief of Java Developer's Journal, was formerly JDJ's longtime Desktop Technologies Editor and is a software developer working on development tools for IBM in Hursley, UK.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

SOA World Latest Stories
In a surprise move Tuesday Oracle wheeled out its Big Data Appliance. That’s the one it said in October would be ready sometime in the first half. Only nobody believed it meant early in the first half. Heck, it’s not even clear anybody thought Oracle could make the first half at al...
A Munich court Thursday found Motorola Mobility guilty of infringing an Apple patent and handed Apple a permanent injunction against two Android smartphones. Apple can enforce the injunction after posting a bond lest MMI succeed in invalidating the slide-to-unlock patent (EP1964022) ...
Quick Response (QR) codes are intended to help direct users quickly and easily to information about products and services, but they are also starting to be used for social engineering exploits. This article looks at the emergence of QR scan scams and the rising concern for users today....
The Chinese company that claims it owns the iPad trademark says it plans to seek a ban on iPad exports out of China, threatening global supplies. According to what a lawyer for Proview Technology (Shenzhen) Co Ltd told Reuters, the firm is petitioning Chinese customs to stop shipment...
Cisco Wednesday filed suit in the European Union’s second-highest court, the General Court in Luxembourg, challenging the European Commission’s rubber stamp last October of Microsoft’s $8.5 billion acquisition of Skype. Cisco says it isn’t opposed to the merger, but figures the EC sh...
2011 was a year of rapid adoption for public and private cloud services. Instant and on-demand server provisioning was the driving force behind the massive growth. On top, cloud server templates and script automation simplified application installation for simple and pre-defined applic...
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