Product Development in Brisbane

FemtoContainer

Credit for this belongs more with William than me. I was talking about it recently with someone, and thought I would post for prosterity

public class FemtoContainer {
Map components = new HashMap();
public void registerComponent(Class class, Object instanceOfComponent){
   components.put(class, instance);
}

public Object instantiateObject(Class classToCreate){
   Constructor[] constructors classToCreate.getConstructors();
   // picking off first — actually probably want to assert that there
   //is only one non-default constructor or something… this is a really short hack for demonstration…. and probably won’t compile.
   Constructor constructor = constructors[0];
   Class[] constructorParameterTypes = constructor.getParameterTypes();
   Object[] constructorParameters=
      new Object[constructorParameterTypes.length];
   for (int i =0; i<constructorParameterTypes.length;i++){
      constructorParameters[i]=components.get(constructorParameterTypes[i]);
}
}

4 Responses to “FemtoContainer”

  1. Stuart Says:

    I’ve been playing with PicoContainer recently and the DefaultPicoContainer implementation does exactly what you’re describing here. You can register instances of particular contructor parameter classes, register the aClass itself, then ask pico for an object of type aClass, and bingo you’re in business.

  2. Pico Freako Says:

    I think the point is that you can get the funcionality that most people use from Pico in one class, rather than having to bother downloading Pico itself and having another dependency in your application.

    As lightweight as Pico is, it is still full of features that a lot of people really don’t need. This is even more lightweight - hence “Femto”.

  3. Stuart Says:

    One for the J2ME guys then?

  4. Rob Says:

    Pico Freako is right. Femto is there because Dependancy Injection should be about controlling the dependancies in your code. Not injecting dependancies on other libraries.

Leave a Reply