Solved Calling Method that requires plugin

Discussion in 'Plugin Development' started by Munnzeh, Sep 6, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    Munnzeh

    Pretty noob question here, but as a solution around the numerous NPExceptions I was getting when attempting to call a timer method from another class, I placed all my Minigame code into one class, which really is not organised and often makes it harder to find where I've missed something. My question is, how would you call a method from another class, which uses the variable plugin, for example the Main class, the timer class, and the class that calls the timer method, obviously calling the timer will return an NPE because the timer is using the variable plugin from the Main class, what is the solution to this?
     
  2. Offline

    timtower Administrator Administrator Moderator

    @Munnzeh You pass the instance of the main class in the constructor of the other classes
     
  3. Offline

    Munnzeh

    @timtower Is it really that simple? Thankyou.

    EDIT: What would I do if i wanted to call Methods from another class to use in the timer method class? Wouldn't that cause errors with the constructors? After trying it, moving the timers to a new class, creating the constructors for main etc, I then had to create a constructor in order to use the methods that were in the other class, lets call it GameCode, that the timer used to start the game, but that's were the errors begin, because you can't have two constructors as far as i know.
     
    Last edited: Sep 6, 2015
  4. Offline

    timtower Administrator Administrator Moderator

    It is indeed that simple.
    Glad that I could help
     
  5. Here is an example of the constructor instance passing:
    Code:
    public class MainClass extends JavaPlugin {
    
    public void onEnable() {
    OtherClass clazz = new OtherClass(this); //Create a new instance of the other class and pass the current instance of the current class in the constructor.
    clazz.initialize(); //Call a random method of the other class
    }
    
    //Another method that get's called later inside the other class
    public void doStuff() {
    System.out.println("Hi");
    }
    
    }
    Code:
    public class OtherClass {
    
    private MainClass plugin; //A variable to store the main class instance
    
    public OtherClass(MainClass plugin) { //Constructor where the main class instance will be passed through
    this.plugin = plugin; //Assign the variable to the passed variable
    }
    
    public void initialize() {
    plugin.doStuff(); //Call a method from the main class
    }
    
    }
    And you can have as many constructors as you want as long as they are different from eachother.
     
Thread Status:
Not open for further replies.

Share This Page