You often need a reference to your main instance (the instance of your class that extends JavaPlugin
) in some of your other classes. There’s two basic concepts for this. Choose whichever you like more.
Method #1: Static Getter
First way is to create a static method called getInstance()
or similar in your main class. You also need a static field in your main class to store a reference to its own instance, and assign your instance as soon as it is created. For example, this:
public class MyPluginMainClass extends JavaPlugin { // Declare the static field private static MyPluginMainClass instance; { // Assign your instance to the field as soon as it's created instance = this; } // Now you can access this method to get your main instance whenever you need it public static MyPluginMainClass getInstance() { return instance; } }
For example, if you have some class called OtherClass
and you need to access something from your main instance’s config inside an event, you can do this:
public class OtherClass implements Listener { @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { String stringFromConfig = MyPluginMainClass.getInstance().getConfig().getString("some-config-option"); } }
Of course it makes sense to not use the getInstance()
everytime if you need it more than once, but to just save the instance inside a field instead:
public class OtherClass implements Listener { private final MyPluginMainClass main = MyPluginMainClass.getInstance(); @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { String stringFromConfig = main.getConfig().getString("some-config-option"); } }
Method #2: Dependency Injection
You can also simply pass a reference to your main instance if the instance of the other class from which you need your main instance is also created by your main instance:
public class MyPluginMainClass extends JavaPlugin { @Override public void onEnable() { getServer().getPluginManager().registerEvents(new OtherClass(this)); } }
Of course, you now have to create a matching Constructor in your other class:
public class OtherClass implements Listener { private final MyPluginMainClass main; public OtherClass(MyPluginMainClass main) { this.main=main; } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { String stringFromConfig = main.getConfig().getString("some-config-option"); } }
TL;DR
Choose one of the methods mentioned above. If you ask what’s better: in terms of OOP, Method #2 is cleaner. Some people might argue that this doesn’t matter, and that Method #1 is more comfortable. Both statements are true, so choose whatever you like.
Join my Discord Server for feedback or support. Just check out the channel #programming-help
🙂