I have a class that does not have the main method. This class is also used by code that is not in my control. This class has a method that takes a String as a parameter, and then based on the value of that String it needs to create different objects. How can I use Guice to create these objects? I think the answer has something to do with Providers, but I'm not sure how to implement it.
Here is the class in question, which doesn't use DI to make the objects:
public class ActionHandler {
public void doSomething(String message) throws Exception {
ActionObject actionObj = null;
if (message.equals("dog")) {
// ActionObjectDog implements ActionObject
actionObj = new ActionObjectDog();
}
else if (message.equals("cat")) {
// ActionObjectCat implements ActionObject
actionObj = new ActionObjectCat();
}
else {
throw new Exception("Action " + message + " not implemented.");
}
actionObj.run();
}
}
I was trying to inject a Provider, but I got stuck because I couldn't figure out how to make the Provider get() method return a specific implementation of ActionObject.
@Inject private Provider<ActionObject> actionObjectProvider;
Any thoughts?