Skip to content

Instantly share code, notes, and snippets.

@JabDoesThings
Last active October 30, 2018 20:00
Show Gist options
  • Save JabDoesThings/0634c2bc04a56729863a69cab0e07985 to your computer and use it in GitHub Desktop.
Save JabDoesThings/0634c2bc04a56729863a69cab0e07985 to your computer and use it in GitHub Desktop.
This is a wrapper for Listener classes that I use for Spigot's Listener API.
package jab.util.spigot;
import org.bukkit.plugin.java.JavaPlugin;
import jab.util.Printable;
/**
* This class is designed to clean up redundant JavaPlugin getters and setters.
*
* @author Jab
*/
public abstract class PluginDependent<P extends JavaPlugin> implements Printable {
/** The JavaPlugin dependency. */
private P plugin;
/**
* Requires a JavaPlugin.
*
* @param plugin
*/
public PluginDependent(P plugin) {
setPlugin(plugin);
}
/**
* Returns the JavaPlugin dependency.
*
* @return
*/
public P getPlugin() {
return this.plugin;
}
/**
* Sets the JavaPlugin dependency.
*
* @param plugin
*/
private void setPlugin(P plugin) {
this.plugin = plugin;
}
}
package jab.util.spigot;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
/**
* This utility class handles common operations of plugin-dependent event-listeners for the Spigot
* Listener API.
*
* @author Jab
* @param <P> The JavaPlugin each implementation depends on.
*/
public abstract class PluginDependentListener<P extends JavaPlugin> extends PluginDependent<P>
implements Listener {
private boolean registered;
/**
* Main constructor.
*
* @param plugin The dependent plug-in.
*/
public PluginDependentListener(@NotNull P plugin) {
super(plugin);
}
/** Registers the events listened to by this Listener. */
public void register() {
if (!registered) {
Bukkit.getServer().getPluginManager().registerEvents(this, getPlugin());
registered = true;
}
}
/** Unregisters the Listener. */
public void unregister() {
if (registered) {
HandlerList.unregisterAll(this);
registered = false;
}
}
@Override
public String getName() {
return getClassName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment