Java 5 and dependency injection
May 11th, 2010
This post is also available in: French
How to dynamically load an implementation using Java 5?
You cannot use Java 6? One of the coolest features brought by this last release is the capability of loading an implementation just using:
ServiceLoader.load(MyInterface.class)
And you were looking for that… I know how boring it is!! It is not public in the API but I found it there. That means that to use ServiceLoader with Java 5 is straight forward:
CharEncoder getEncoder(String encodingName) { Iterator ps = Service.providers(MyInterface.class); while (ps.hasNext()) { MyInterface myInterface = (MyInterface)ps.next(); MyImpl myImpl = MyInterface.getImpl(implName); if (myImpl != null) return myImpl; } return null; }
That’s it
English
Français