问题
I am trying to make a plugin that starts a Scheduler task with this method:
public void newCountdown() {
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
player.sendMessage("Hey");
}
}
}, 0, 20);
}
The problem is, when I try to call the method, it says it needs to be a static method. Then, when i change it to static the first parameter "this" says it cannot be used in a static context.
When the method is not static, the scheduleSyncRepeatingTask
shows this error:
The method scheduleSyncRepeatingTask(Plugin, Runnable, long, long) in the type BukkitScheduler is not applicable for the arguments (activateDevMode, new Runnable(){}, int, int)
When I try any of the quick fixes it gives me, it will always result in another error.
Is there a way to reference this
from the Main class without having to make my method static?
回答1:
The reason this isn't working is because static and this never go together. An easy way to think about it is that static
removes the object-oriented part of Java. this
is a keyword that points to the current instance of your class, and cannot be used with static
because using a static
variable is like completely removing instances all together.
You will have to change this
to an instance of your Main
class (the one that extends JavaPlugin
). You can initialize a static variable onEnable()
to store the instance
public static Main that; //"Main" will be replaced with the name of your Main class
@Override
public void onEnable(){
//set that to an instance of your Main class (this)
that = this;
}
@Override
public void onDisable(){
//set that to null to prevent memory leaks
that = null;
}
Now, you can make your newCountdown()
method static by replacing that
with this
public static void newCountdown() {
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.that, new Runnable() {
public void run() {
for(Player player : Bukkit.getServer().getOnlinePlayers()){
player.sendMessage("Hey");
}
}
}, 0, 20);
}
来源:https://stackoverflow.com/questions/31257935/referencing-this-from-a-class-that-is-not-extending-javaplugin