如何使用 Bukkit API 触发事件?

How to fire events using Bukkit API?

我正在研究如何使用 Bukkit 创建和触发事件 API。

public class PlayerDisconnect implements Listener {
    @EventHandler
    public void onQuit(PlayerQuitEvent event){
        //code
    }
}

我的意思是,方法的名称并不重要(在本例中 onQuit,我可以使用 onDisconnectonLeave 等,它仍然会被调用通过 PlayerQuitEvent),它使用 PlayerQuitEvent 作为参数调用每个方法。我希望能够复制这种行为。

您可以使用 Bukkit 事件创建和调用您自己的自定义事件 API。 Spigot 在 Event API.

上有一个很好的入门教程

Cancellable 事件的一个简单示例,需要 Player:

...
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

public class MyCustomEvent extends Event implements Cancellable
{
    private static final HandlerList handlers = new HandlerList();

    private final Player player;
    private boolean cancelled;

    public MyCustomEvent(Player player)
    {
        this.player = player;
    }

    public static HandlerList getHandlerList()
    {
        return handlers;
    }

    public Player getPlayer()
    {
        return this.player;
    }

    public HandlerList getHandlers()
    {
        return handlers;
    }

    @Override
    public boolean isCancelled() 
    {
        return cancelled;
    }

    @Override
    public void setCancelled(boolean cancelled) 
    {
        this.cancelled = cancelled;
    }

}

然后您可以像这样在自定义事件的其他地方调用它

...
MyCustomEvent event = new MyCustomEvent(player);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
    return;
...

最后,您将像收听任何其他事件一样收听该事件:

...
@EventHandler
public void onMyCustomEvent(MyCustomEvent event){
    Player player = event.getPlayer();
    ...
}

你应该使用 PluginManager#callEvent(Event).

public class CustomEvent extends Event implements Cancellable {
    private static final HandlerList handlers = new HandlerList();

    private final String a;
    private final int b;
    private boolean cancelled;

    public CustomEvent(String a, int b) {
        this.a = a;
        this.b = b;
    }

    public String getA() {
        return a;
    }

    public int getB() {
        return b;
    }

    @Override
    public boolean isCancelled() {
        return cancelled;
    }
 
    @Override
    public void setCancelled(boolean cancelled) {
        this.cancelled = cancelled;
    }

    @Override
    public HandlerList getHandlers() {
        return handlers;
    }

    public static HandlerList getHandlerList() {
        return handlers;
    }
}
CustomEvent event = new CustomEvent("some data", 5);
Server server = ...
server.getPluginManager().callEvent(event);
if (event.isCancelled()) return;
// Do event

the official tutorial and this community tutorial


如果你想在非 Bukkit 插件项目中使用 Bukkit 事件系统,你可以添加 Bukkit API 作为依赖项(只是 API,而不是实现它的服务器)。