In all of the Guice examples I have found, getting an instance involves calling Injector.getInstance() with the concrete class as a parameter. Is there a way to get an instance from Guice using only the interface?
public interface Interface {}
public class Concrete implements Interface {}
Interface instance = injector.getInstance(Interface.class);
Thanks
Actually that’s exactly what Guice is made for.
In order to make getInstance() work with an interface you’ll need to first bind an implementation of that interface in your module.
So you’ll need a class that looks something like this:
Then when you create your injector you just need to pass an instance of your module in:
Now your call to
injector.getInstance(Interface.class)should return a new instance of Concrete using the default constructor.Of course there are many many more ways you can do bindings but this is probably the most straight forward.