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 –
– 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:
I guess, that everything is clear to everyone. If method
is present in the class of
object then call it. And here’s the implementation of the method:
String methodName, boolean param) {
Method method = null;
method = clazz.getDeclaredMethod(methodName,
new Class[] { Boolean.TYPE });
} catch (NoSuchMethodException e) { }
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!
The Ruby on Rails addict, industrial photographer and amateur electronic music composer. In the mean time I build great web applications, contribute to OSS and help AVAAZ to save Great Barrier Reef.
Leave a Reply