Main Instance

What is a main class instance?
If you're familiar with basic java you should be pretty familiar with what an instance of a class is. However, if you are not, an instance of a class is a live java object that conforms to said class. Bukkit automatically creates an instance of your main class when it starts up which represents your main class instance.

Why do we care about a main class instance?
There are several methods in Bukkit and spigot that require a Plugin instance to be used effectively, some common ones include starting runnables, registering events and registering commands. For example, the method Bukkit.getPluginManager().registerEvents(listener, plugin);
takes a plugin instance for it's second parameter. If you are running this method from your main class instance (for example, on your onEnable() method) you can just use this to denote the current class instance.

How do I get my main class instance from other places?
If you are running code statically, or from a different class, you can't simply use this as you are no longer in your main class's scope. There are several ways of getting your main class instance to other areas.

  • Passing it in a constructor. This is a really common way of getting your Main class.
    Example:
public class <Name> 
{

	private Main main;

	public <Name>(Main main)
    {
    	this.main = main;
    }

}
  • Using a static variable. This is a much easier and just as safe way, we are creating a static variable to store our main instance.
    Example:
public class <Name> extends JavaPlugin 
{

  private static <Name> mainInstance;

  @Override
  public void onEnable() 
  {
    mainInstance = this;
  }

  public static <Name> getMain() 
  {
    return mainInstance;
  }
  
}