This may not be the best solution, but it may work for you.
You can implement a provider that allows you to provide dynamic input. Then ask the provider to enter the classes they need so that you can create your object that you need dynamically.
Here is a snippet from the Provider JavaDoc :
A provider instance can always be selected in the implementation class, instead of directly entering T. This can give you access to multiple instances, instances that you want to mutate and discard safely, instances that are not available (for example, using @RequestScoped object from @SessionScoped object) or instances that will be initialized lazily.
It may look something like this: I personally think that it is normal to inject an injector into a provider, because it is part of the injection framework. The goal is to leave the Injector outside of your application code, and that certainly does.
public class FooProvider implements Provider<Foo> @Inject private Injector injector; private String input; public void setInput(String input){ this.input = input; } @Override public Foo get(){ if(input.equals("bar")){ injector.getInstance(Bar.class);
Then in another place ...
public class Goo{ @Inject Provider<Foo> fooProvider; public Foo goo(String input){ fooProvider.setInput(input); return fooProvider.get(); } }
The key is to make sure that each provider instance is unique for each injection point, which, in my opinion, is the default. Since this provider has a mutable state, you cannot force it to be thrown around your application (and possibly do the wrong thing in a multi-threaded environment) if that is not what you intend to do. Then you will need to take extra precautions.
source share