Wednesday, April 16, 2008

Simple injection util

Dependency injection is really a mainstrem in today's Java Programming. There are entire Framework, that are based on it, like Spring, Google Guice or Picocontainer.
Also called inversion of control, this pattern helps to reduce dependecies and is especially useful in unit testing.

By the way, we'll now introduce a simple Utility class to inject instances of object at field level.
static public void injectField(Object objectToBeInjected, String fieldName,
Object objectToInject) throws NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Class clazz = objectToBeInjected.getClass();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(objectToBeInjected, objectToInject);
}

This approach has a big disadvantage: it doesn't catch the attributes, that belog to superclasses, because of clazz.getDeclaredField(fieldName).
I thought that Class#getField(String) could help in this case but I was wrong, because this method retrieves recursively only the fields, which are public.

This article gives me the right solution, that is:
static public Field getDeclaredField(Object object, String name)
throws NoSuchFieldException {
Field field = null;
Class clazz = object.getClass();
do {
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) { }
} while (field == null & (clazz = clazz.getSuperclass()) != null);

if (field == null) {
throw new NoSuchFieldException();
}

return field;
}


So in order to get the desired result, you can now use this implementation.

No comments: