Question

I am using Guice to build my application and I have a peculiar situation. I have a property file with a map of my interface and implementation classes such as -

interface = Implclass

I would like to bind the interface.class to my implclass.class

So that when I request injector.getInstance(MyInterface.class) Guice can return me an instance of my Impl class.

Is this possible ?

Was it helpful?

Solution

You could do something very simple like this:

class Module extends AbstractModule {

  Properties properties;

  Module(Properties properties) {
    this.properties = properties;
  }

  @Override
  protected void configure() {
    for (Entry<Object, Object> entry: properties.entrySet()) {
      try {
        Class<?> abstractClass = Class.forName((String)entry.getKey());
        Class implementation = Class.forName((String)entry.getValue());
        bind(abstractClass).to(implementation);
      } catch (ClassNotFoundException e) {
        //Handle e
      }
    }
  }
}

Note that the properties file will need to contain fully qualified class names for this to work. I noticed your question uses short class names. Have a look at this question to add support for that.

Spring has extensive support for XML based configuration, which might be a better option depending on what you're trying to do. Keeping your bindings in code is nice because they survive refactoring.

And if you're trying to allow clients to add functionality to your application SPI might be a better bet.

OTHER TIPS

Google says yes:

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
  }
}

To get a Class given a String of the class name, use Class.forName.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top