Reflection and Singletons

*** Posted on All rights reserved ***

Java reflection is one of those tools that you may go for years without using, and never miss it. Until the day comes that you have to invoke methods without knowing what they are in advance. When that happens, reflection will be the thing that would prevent you from jumping off the nearest cliff. IF you do it right.

Invoking a method by reflection is fairly straight forward: You get a Class object that describes the class of the method that you are trying to use, get the method you want, and create a method object that represents that method. I wont go into the details or code for this, but you can find a fairly comprehensive guide here.

The tricky part starts when you attempt to invoke the method. The signature for invoking a method requires an object that the method is invoked on, and the list of parameters. In other words, if you are trying to invoke method myMethod() from Class MyClass, the reflection API wants to know which object of MyClass do you want to call that method. The API even goes a step further and lets you specify that a new object should be created for this by invoking the Class.newInstance() method which calls the default no-args constructor of the class. So far so good.

But what happens if the class you are trying to call is a singleton? (I know I said that Java doesn’t have real singletons, but what it does have behaves enough like a singleton to cause this problem) Remember that in a singleton, there are no public constructors, and the only way to get an object of the class is by calling getInstance(). Unfortunately, if you are using reflection you can run into a situation where the object you are invoking at any particular iteration may or may not be a singleton and you wont know in advance, and calling newInstance() on a singleton will definitely not work as advertised. So what do you do?

What you can try to do is something like this:

Object obj = null;
Class<?> cls = Class.forName(className);
Method methodIWantToInvoke = cls.getMethod(methodName, Params);

     Method getinst = cls.getMethod("getInstance",null);
     obj = getinst.invoke(null, null);
     }catch(NoSuchMethodException n){
     try {
         obj = cls.newInstance();
     } catch (InstantiationException e) {
Object result = methodIWantToInvoke.invoke(obj, params);

What you are doing here is using reflection to get an object so that you can use reflection to invoke a method. 🙂

If the Class object cls describes a class that is a singleton, then the request to getMethod(getInstance(), null) will give ou back a Method object that you can invoke to get the instance of the singleton you need. If it isn’t a singleton, it will throw a MethodNotFoundException, in which case you know you can use plain old newInstance you invoke the constructor.  Either way, but the end of this, you can an Object that you can then pass to the method you originally wanted to invoke in order to invoke it.

Note that the order of actions here is arbitrary: You can just as easily call newInstance first and then (upon getting an IllegalAccessException) try getInstance(). You can also combine this with a static factory method to allow calling of constructors other than the no-args, which adds to your flexibility.

Using reflection is realy not as complicated as it might seem, but there are (at least) two things you must by mindful of:

1. Reflection is slow and heavy. It adds a lot of overhead to your code and should be used very judiciously (for a bit of insight to the overhead, checkout Dennis Sosnoski’s Java programming dynamics article. It’s a little dated, and reflection HAS become more efficient, but it’s still no where near directly coding)

2. One of the more common uses of reflection is with serialization, to examine and use de-serialized objects. This is exactly where Java Singletons fails. If you have an Object that was serialized and then deserialized in different JVMs, even though you can successfully call its getInstance() method with the code above, you are still not getting the same object.

Good luck, and happy coding,



Java Singletons don’t exist.

*** Posted on All rights reserved ***

When I first started in my current project I set down to a code review with the lead programmer to see “my” project. At some point during the review, the man pointed to a certain class that was being used as part of the startup sequence for the application and said “this should be reimplemented as a singelton”. Up until then I was following him closely, but that statement took me by surprise, because as far as I knew, singletons don’t exist in Java.

To understand why, we have to look at the definition of a Singelton:

A singleton is a pattern that permits exactly one object that is needed to coordinate actions across the system.

In other words, whereever I am, if I try to use a class that is defined as a singleton, I would always, always, get the SAME object.  Usually, a native implementation of a Singleton looks something like this:

public final class MySingleton{

private MySingelton me=null;

private MySingleton(){
   ...instantiation code here...

public Mysingelton getInstance(){
  if (null==me) me = new MySingelton();
  return me;


As you can see, MySingleton has no public contractors. It can’t be directly instantiated or inherited. You can only get a MySingleton Object by calling getInstance(), which always returns the same object. This makes the singleton very handy for coordinating actions across a system. System states, for example, can be saved as singletons, as can factories, shared queues (a synchronized singleton), thread states, etc. Everywhere in the system that you can the singleton’s name, you’re guarantied to have the exact same object returned to you.

So why are there no Java singletons? Clearly the code above is written in Java and would run in Java, and would function as expected in a Java program. The reason this is not a singleton is the last part of the singleton definition “across the system”.

Consider: In C++, I can use code very much like the one above to tell me if a program has been launched. On the first time that the program runs, it asks for the singleton object, gets it (after it has been allocated by the system) and modifies it to indicate that it had been launched. If the program is then launched again, the second instance of the program would request and get the SAME singleton, see that the “running” state has already been set, and exit. The singleton is used across the system in coordinate states.

In Java, on the other hand, every program instance would run in its own instance of the JVM. This means that when the second instance of the program is launched, it would NOT get the same object as the first instance, but rather it would get the instance that has just been instantiated in its own JVM. The code above can coordinate across the same JVM, but it fails to coordinate across the system. Therefore, it does not qualify as a true singleton.

This may seem like splitting hairs, but it’s a very important thing to know. The guy I set with in the code review was pointing at a class who’s job was to make sure only one instance of the application would ever launch. We work on a project that does network measurements and topographies. It sends out packets with different addresses and TTLs and uses the returns to map the Internet. If we have two instances of the application running at the same time, we may not know which packet was sent by which instance, and our results would be compromised. Furthermore: We allow our users to run the application as a service, or as a standalone GUI based program. If we don’t have mutual exclusion, we can run into a situation where a user had installed the service AND the GUI, and starts both, thinking that the GUI just reflects the service. This could very easily lead to corruption in our data, and problems in the whole research.  All because Java singletons aren’t really singletons.

The good news is that in 95% of the cases, the code above would work quite nicely as a singleton. So long as you are staying within the JVM, it’s fine. For the last 5%, there are workarounds that can make mutual exclusion possible in Java. I will post about that some other time, though.

Good Coding,


De-Coupling MVC with Facade classes

Please note: The original url for this post is:
If you are reading this on any other web site, this content is stolen.

One of the best and worse things about Java is the easy way it allows you to create GUI elements and their associated commands together, which makes for very simple way to develop user interfaces.  This is one of the best features because it allows developers to concentrate on developing program logic, and simplifies interacting with the user to a level attainable even by beginners. It is one of the worse because this integration can lead to a very tightly coupled View and Control. Two of the three major part of the Model View Control (MVC) design pattern. MVC calls for each part to be separate and independent, so as to allow better code re-usability, easier maintenance, and better task grouping. This is certainly possible in Java, but requires more work then just building the control logic right into the GUI classes, and so developers don’t always bother to make the separation.

My current project, for instance, uses exactly this kind of tight coupling, which I’m trying to undo. I am looking to separate the view and the controller into independent code, and actually into different programs. The controller and model code requires administrative privileges to run and need to run all the time, while the GUI code requires just regular user privileges and only when the user wants it. So I’m separating them into two separate programs which will communicate over a shared channel.

The problem, as I mention, is that my GUI and the actions that it creates are coupled very tightly with the controller code itself. There is no point were controller threads are registered on GUI components and get notify()ed of state changes (yes, a Java method as a verb. Live with it). Rather ActionListeners directly invoke methods in the controller classes to make things happen in the program. It works, but it’s a bit messy, and can be a real problem considering that in the new paradigm, all commands and feedback are going to travel over one point of contact (the Channel). There are twenty-some methods being invoked from three classes that are part of the program cotroller. All of thoes need to be brought under one roof.  I could rewrite every one of them to call my ChannelCommunicator class instead, and ask it to transmit the command to the controller, but this is both tedious and potentially dangarous since I don’t know what else in the code is dependet on those methods being invoked in this certain way.

Facade classes to the recue! A facade class is a class which presents a simplified view of a subsystem and makes it easier to use. In my particular case, this means that I can create a facade for each of the three classes mentioned above. The facade function as an abstraction layer which implements the methods that my GUI classes expect to finds on on side, and passes calls to the ChannelCommunicator in a unified way on the other side. The GUI is happy because nothing has changes (except for the class name), the ChannelCommunicator is happy because it gets one type of call and doesn’t need to deal with special cases, and I’m happy because I don’t have to re-write every method that’s involved! Fantastic!

The thing to remember about this paradigm is that your facades come in pairs, and thus there is a certain amount of duplication involved. Why pairs? bacause I have to put a facade for the controller between the GUI and the ChannelCommunicator and, on the other side, I have to put a facade for the GUI between the ChannelCommunicator and the controller. The nice part about it is that these classes are really nothing more than parsers which translate the specific format of each command into a standard format the communicator can understand, and parse it back on the other side, so the logic involved is not very complicated. Still, this is a stopgap solution to allow MVC decoupling without having to redesign major parts of the code. In a perfect world you’d be better off re-writing the methods. But then, in a perfect world you wouldn’t have this problem to begin with. 🙂


P.S. To learn more about design patterned I would highly recommand Bruce Eckel‘s book Thinking in Patterns, which is available to download for free.

Overloading Constructors in PHP

Anyone who’s ever programmed in something like Java has probably written an overloaded constructor or two in their life. The ability to use different constructors for different circumstances is fundamental to both the polymorphism and code-reusability parts of OOP, and are amongst the fundamental tools of the trade.

PHP, having started out as a simple web-interaction language, and having only recently added real support for OOP programming, does not support constructor overloading. Annoyingly, Netbeans 6.5.1 doesn’t kick up any sort of warning if you attempt to overload a variable. The page simply would not render, without any mention of why. To make matters worse: it seems that this is such a fundamental issue in PHP that it doesn’t even get to a point where you can attach a debugger and see where things are breaking. You either know this, or you end up sitting in front of an empty browser window scratching your head.

So how can you “overload” constructors in PHP anyway? by using optional arguments, of course!

consider the following function declaration:

class PHPExample{
    public function __construct(array $inputArray="", $in="")

The function is obviously the (one and only) constructor method for its class. Yet any of the foolowing calls will invoke it correctly:

$A = new PHPExample();
$A = new PHPExample(array("A","B","C"));
$A = new PHPExample(,4);
$A = new PHPExample(array("A","B","C"), 4);

The key to this “psudo-overloading” is the list of arguments a function can take. In PHP, you can designate a default value for an argument. For example:

function add ($i, $j=1){
   $k= $i+$j;
   echo $k;

If you called the function add(1,2) you would get the response 3.
However, if you called add(1) the function will use it’s default value, and will respond with 2.

So what happens if the default value is null (ie “”)? Then the argument becomes optional. If the function call specifies the argument, it is used. If the call doesn’t have a value for the argument, the argument’s default value (null) is used, and the argument is thus ignored.

So now we have our “psudo-overloading”: Instead of writing different constructors for each set of arguments, we simply write the different senarios into the single constractor. For example:

public function __construct($in=""){
   if(is_array($in)) {

There just  are a couple of things to keep in mind when using optional variables:

First, optional arguments must come at the END of the argument list:

public function __construct(array $inputArray, $in="") Good

public function __construct(array $inputArray="", $in) Not Good

Second, you must account for optional arguments that you are not using, if you are using arguments that come later in the argument list:

$A = new PHPExample(,4); The comma tells PHP that the 4 is the second argument in the list.

This is by no means a perfect method, and one must hope that eventually PHP will come out with a version that does support constructor overloading. Until then, this is a workable, if possibly a little messy, workaround.