Calling Optional Methods

Posted: October 21st, 2005 | Filed under: Programming, Tips | No Comments »

Today I had another interesting task — to make splash screen window be always on top of everything else on the screen. Yes, and it’s all in Java. I know that Java 1.5.0+ already has a nice method to accomplish this –

setAlwaysOnTop(boolean)

– but what about our 1.4.2 compatibility? I wasn’t able to find any methods for doing this in 1.4.x and decided to add support at least for our users at 1.5.x . The next question was *how* to call this method without breaking compatibility with 1.4.x?

Sometime I get really scared of things I come up to. The approach I took here is based on our ability to query meta-data for everything in Java. I decided that I could scan a given class for a method required and if it’s there, to call it. Here’s what I wanted the invokation to look like:

RTUtils.callIfPresent(window, "setAlwaysOnTop", true);

I guess, that everything is clear to everyone. If method

setAlwaysOnTop(boolean)

is present in the class of

window

object then call it. And here’s the implementation of the method:

public static void callIfPresent(Object obj,
String methodName, boolean param) {
  Class clazz = obj.getClass();
Method method = null;
  try {
method = clazz.getDeclaredMethod(methodName,
new Class[] { Boolean.TYPE });
} catch (NoSuchMethodException e)  { }
  if (method != null) {
try {
method.invoke(obj,
new Object[] { Boolean.valueOf(param) });
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to invoke " +
"detected method (" + methodName + ")", e);
}
}
}

In the first part we try to find a method with the given name. If the method is there, we continue with calling it. If it isn’t, well, that’s OK. I don’t see any complications here, do you?

… and it works like charm!



Leave a Reply