我们尝试用 Guice 重构一个项目。这个想法是将所有Language接口绑定到一个 concreate 对象,如French或Polish。
我们有一个绑定模块:
public class StandardModule extends AbstractModule {
@Override
protected void configure() {
bind(Language.class).to(Polish.class);
}
}
还有一个使用这个注入对象的类(AboutDialog.java):
@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();
}
结果是:
java.lang.NullPointerException at net.sf.jmoney.gui.AboutDialog.<init>(AboutDialog.java:67)
第 67 行是:
this.setTitle(language.getLanguageInUse().getString("AboutDialog.title"));
我们的界面是:
public interface Language {
public ResourceBundle getLanguageInUse();
}
波兰语课是:
public class Polish implements Language {
private ResourceBundle languageInUse;
public Polish() {
languageInUse = ResourceBundle.getBundle(Constants.LANGUAGE_PL);
}
public ResourceBundle getLanguageInUse() {
return languageInUse;
}
}
我们迷路了...