Home > Java, Programming > Java 5 and dependency injection

Java 5 and dependency injection

May 11th, 2010 jmguilla

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

Categories: Java, Programming Tags: ,
  1. No comments yet.
  1. August 11th, 2014 at 23:34 | #1
Comments are closed.