Stuperfied
Stuperfied

Reputation: 318

In Java, how can I access the main class dynamically?

I am trying to access a variable of the main class. The problem is that I want to make my code completely modular so that I can build on it and create a library. The problem I am having is that in order access the variable I must use the name of the main class as such:

    // this is in the main class which we will call "MyPlugin"
    public class MyPlugin extends JavaPlugin {
        public static String compath = "CommandFileName";

        @Override
        public void onEnable() {
            this.getServer().getPluginManager().registerEvents(new MyListener(this), this);
        }
    }

    // this is in the listener class which we will call "MyListener"
    public MyListener(Plugin instance) {
        Plugin plugin = instance;
        path = MyPlugin.compath;    // <-- the problem...

My first thought was that I should be able to simply do this:

    path = plugin.compath;

however for some reason the plugin object does not contain the compath variable. Is there a way to access a variable of the main class without using its name?

Now more indepth for those who may like to think around the purpose. MyListener is going to reference a config file of type yml. For whatever reason, the name of the key's in the config yml file may be different in future. My idea was to put the names in the main class so they could be referenced by MyListener. Such an approach would more centralize the list of names and prevent extensive changes to multiple classes in future.

Upvotes: 0

Views: 110

Answers (2)

Stephen C
Stephen C

Reputation: 718758

The simple answer is to declare a getter in the JavaPlugin API.

There are two things that you have done in your initial design that are making your task complicated: you have made the variable static and you have made it public. Both of these are bad OO design:

  • Static variables are bad for testability and can't be used polymorphically (or "dynamically" as you phrase it).
  • Public variables are bad for abstraction. (Especially non-final ones!)

Anyhow, this is how I would implement this:

public abstract class MyPluginBase extends JavaPlugin {
    public abstract String getCompath();
    ....
}

public class MyPlugin extends MyPluginBase {
    @Override
    public String getCompath() {
        return "CommandFileName";
    }

    @Override
    public void onEnable() {
        this.getServer().getPluginManager().registerEvents(
               new MyListener(this), this);
    }
}

public MyListener(MyPluginBase instance) {
    path = instance.getCompath();
    ...
}

Upvotes: 1

Jan
Jan

Reputation: 1504

I think you wanted

public MyListener(MyPlugin instance) {
        MyPlugin plugin = instance;
        path = plugin.compath;

The problem is that you use Plugin instead of MyPlugin

Upvotes: 0

Related Questions