我能够非常快速地学习和拾取东西,但这仍然令我感到困惑:
这是在主类(DCFlags)中:
private WGCustomFlagsPlugin pluginWGCustomFlags;
private WorldGuardPlugin pluginWorldGuard;
private DCPvPToggle pluginDCPvPToggle;
private RegionListener listener;
public WGCustomFlagsPlugin getWGCFP(){
return this.pluginWGCustomFlags;
}
public WorldGuardPlugin getWGP() {
return this.pluginWorldGuard;
}
public DCPvPToggle getPPT(){
return this.pluginDCPvPToggle;
}
public void onEnable(){
this.pluginWorldGuard = Utils.getWorldGuard(this);
this.pluginWGCustomFlags = Utils.getWGCustomFlags(this);
this.pluginDCPvPToggle = Utils.getDCPvPToggle(this);
this.listener = new RegionListener(this);
}
这是在另一个类(Utils)中:
public static WGCustomFlagsPlugin getWGCustomFlags(DCFlags plugin){
Plugin wgcf = plugin.getServer().getPluginManager().getPlugin("WGCustomFlags");
if ((wgcf == null) || (!(wgcf instanceof WGCustomFlagsPlugin))) {
return null;
}
return (WGCustomFlagsPlugin)wgcf;
}
public static WorldGuardPlugin getWorldGuard(DCFlags plugin){
Plugin wg = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
if ((wg == null) || (!(wg instanceof WorldGuardPlugin))) {
return null;
}
return (WorldGuardPlugin)wg;
}
public static DCPvPToggle getDCPvPToggle(DCFlags plugin){
Plugin ppt = plugin.getServer().getPluginManager().getPlugin("DCPvPToggle");
if ((ppt == null) || (!(ppt instanceof DCPvPToggle))) {
return null;
}
return (DCPvPToggle)ppt;
}
我知道这是因为能够使用其他插件的方法,但是什么是“这个”。为什么需要?
答案 0 :(得分:4)
this
始终是对当前对象的引用。
在这些例子中,不需要它。但是,请考虑以下事项:
class C {
private String name;
public void setName(String name) {
this.name = name;
}
}
在这种情况下,this
关键字用于区分传递给name
方法的局部变量 setName
和字段 this.name
,在类中声明。
还要考虑以下事项:
class C {
private String name;
public void doSomething(final String name) {
// here, `this` is an instance of C
new Runnable() {
@Override
public void run() {
// here, `this` is an instance of Runnable
System.out.println(name);
// prints the name passed to the method
System.out.println(this.name);
// error: Runnable has no field name
System.out.println(C.this.name);
// prints the enclosing class's name
}
}.run();
}
}
在其他一些语言中,例如Python,总是需要使用self.
(粗略语义等价于this.
)来引用字段。在Java中,它不是。