Search code examples
javanullpointerexceptionguicecode-injection

Guice injection null pointer


We try to refactoring a project with Guice. The idea is to bind all the Language interface to a concreate object like French or Polish.

We have a module for binding:

public class StandardModule extends AbstractModule {

    @Override
    protected void configure() {

       bind(Language.class).to(Polish.class);

    }
 }

And a classe (AboutDialog.java) that use this injected object :

@Inject Language language;

public AboutDialog(JFrame parent) {
    super(parent, "", true);
    this.language=language;
    this.setTitle(language.getLanguageInUse().getString("AboutDialog.title"));
    this.parent = parent;
    try {
        jbInit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    pack();
}

And we have as result:

java.lang.NullPointerException at net.sf.jmoney.gui.AboutDialog.<init>(AboutDialog.java:67)

Line 67 is:

this.setTitle(language.getLanguageInUse().getString("AboutDialog.title"));

Our interface is:

public interface Language {

    public ResourceBundle getLanguageInUse();
}

And the Polish class is:

public class Polish implements Language {

    private ResourceBundle languageInUse;

    public Polish() {
        languageInUse = ResourceBundle.getBundle(Constants.LANGUAGE_PL);
    }

    public ResourceBundle getLanguageInUse() {
        return languageInUse;
    }


}

We are lost...


Solution

  • I assume that your are not creating your AboutDialog with the help of Guice.

    What you could do is use injector.injectMembers(this) where this is the AboutDialog.

    The best way would be that the AboutDialog will be created by Guice, so all members will be injected.