【发布时间】:2014-05-07 22:32:20
【问题描述】:
所以,我一直在开发一个插件。一切都很顺利,直到我偶然发现了一个问题。我正在使用单独的 Listener (implements Listener) 类来管理我的事件,但对于其中一些,我需要访问 JavaPlugin 方法,例如获取配置文件。
在我的侦听器类中使用构造函数 below 有效,但如果我尝试在另一个类中使用相同的东西,Eclipse 会给它一个可爱的红色下划线,表示 blank final field plugin may have not been initialized
private final MainClass plugin;
public ListenerClass(MainClass instance){
this.plugin = instance;
}
如前所述,上述代码有效,但仅适用于一位听众。
below 的构造函数在使用返回对象的方法时会抛出 NPE。我不知道这是因为插件实例实际上返回为null,或者如果没有句柄if它是null。
// The only difference between this constructor and the last is that the final
// modifier was removed.
private MainClass plugin;
public ListenerClass(MainClass instance){
this.plugin = instance;
}
FileConfiguration config = plugin.getConfig(); // throws NPE
// Let's pretend that the line above isn't there, and I just use the getConfig() method instead.
@EventHandler
public void onJoin(PlayerJoinEvent event){
if(plugin.getConfig().getString("Strings.cat-toy").toLowerCase().equals("string")){ // throws NPE
// do stuff
}
}
【问题讨论】: