Guice Tutorial - 05 - Default interface implementation


Sometimes we have to define interface and write only one class which implements it, for example we see possibility of extending in future or we want to make our class final to prohibit making subclasses of this type or maybe we want to have one default implementation of interface. This goal could be obtained with Guice.

Interface and class

We have class:
public class PdfReportWriter implements ReportWriter{
    public void write() {
        // ...
which implements our interface and it is only class which do this. Interface looks so:
public interface ReportWriter {
    void write();
By the ImplementedBy annotation we say to Guice that if I ask for object of type ReportWriter than we should by default obtain object of type PdfReportWriter. Let's test it:
public void shouldGetImplementationOfInterface(){
    Injector sut = Guice.createInjector();
    ReportWriter reportWriter = sut.getInstance(ReportWriter.class);
    assertTrue(reportWriter instanceof PdfReportWriter);
And the test passes.


When we have interface which has only one implementation or we want to make this class default implementation for interface than we could use ImplementedBy annotation in Guice. Sources are available here.

No comments:

Post a Comment