0

我能够非常快速地学习和学习东西,但这仍然让我感到困惑:

这是在主类(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;
}

我知道这是为了能够使用其他插件的方法,但什么是“this”。为什么需要它?

4

1 回答 1

4

this始终是对当前对象的引用。

在这些示例中,不需要它。但是,请考虑以下事项:

class C {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

}

在这种情况下,this关键字用于区分传递给方法的局部变量 和在类中声明的字段。namesetName 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 中,它不是。

于 2013-06-09T15:40:54.460 回答