Tuesday, December 29, 2009

Mycila Guice

I've create some weeks ago another small project: Mycila Guice. This project acts as an extension for Google Guice injector framework. It is used in other projects i am working on.
  • ServiceLoader plugin (enables injection into loaded services)
  • JSR250 supports improved from GuicyFruit
  • Custom Injector with more useful methods which consider the whole Injector hierarchy
  • CachedScope to cache your binding for a specific duration
See: http://code.mycila.com/wiki/MycilaGuice

Sunday, December 20, 2009

Get all declared methods of a class hierarchy

When working on Mycila Event library, I needed to get all annotated method of a class' hierarchy. One simple solution is to iterate over all classes using class.getSuperClass() and call getDeclaredMethods(). But you will quickly see this doesn't work since it does not consider that a method can be overridden.

To remove overridden methods, you have you check also method signatures. The class MethodSignature can help you doing so. You can write a method like this to recover all declared methods of a class and its super classes:

public static Iterable<Method> getAllDeclaredMethods(Class<?> clazz) {
LinkedHashMap<MethodSignature, Method> all = new LinkedHashMap<MethodSignature, Method>();
while (clazz != null && clazz != Object.class) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
MethodSignature signature = MethodSignature.of(method);
if (!all.containsKey(signature))
all.put(signature, method);
}
clazz = clazz.getSuperclass();
}
return new LinkedList<Method>(all.values());
}

You can even improve this code by avoiding creating the MethodSignature of a method: if a method is private or final, you know that this method cannot be overridden.