Reputation: 25
I wrote the getPlugin()
method to be able to get the main class from another class.
public class Main extends JavaPlugin {
public Main getPlugin() {
return this;
}
}
But when I try to call it...
public class Arena {
private Main plugin = Main.getPlugin();
}
...Eclipse gives me the following error:
Cannot make a static reference to the non-static method getPlugin() from the type Main
I have used static, but static gives me issue's in a lot of different places, and I've seen that static is usually a bad way of doing stuff. Causes memory leaks and stuff.
I have tried using getters and setters, but those need to be static too? The code I've been using is very messy and I'd like to find a cleaner way of accessing another class.
Upvotes: 1
Views: 103
Reputation:
This problem occurs because there already is a getPlugin()
method in the JavaPlugin
superclass, so when you do Main.getPlugin()
you are trying to call the non-static one.
Also, your own method is non-static.
Here is how I do.
You have to use a different name and make it static. Also, you should initialize its value on onEnable()
.
public final class Example extends JavaPlugin {
private static Plugin main;
public static Plugin getMain() {
return main;
}
@Override
public void onEnable() {
main = this;
}
}
Upvotes: 0
Reputation: 934
If you want to avoid using static methods, you need to pass variables as a parameter to the constructor of objects. In your example, it would work like this:
public class Arena {
private final Main plugin;
public Arena(Plugin plugin) {
this.plugin = plugin;
}
}
And then you can create an Arena from your main plugin class, and pass in this
as a parameter:
public class Main extends JavaPlugin {
@Override
public void onEnable() {
Arena arena = new Arena(this);
}
}
Upvotes: 1