Solved Store instance of mainclass

Discussion in 'Plugin Development' started by Robnoo, Dec 11, 2018.

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

    Robnoo

    Hi,

    I used to use a parameter in the constructor of a class if I wanted to store an instance of the Main class.

    Code:
    public class Main extends JavaPlugin {
    
    public void onEnable(){
    
    getCommand("info").setExecutor(new Commands(this));
    
    }
    
    }
    
    public class Commands implements CommandExecutor {
    
    Main plugin;
    
    public Commands(Main instance){
    plugin = instance;
    }
    
    }
    
    I wanted to make it easier so that constructors don't need these parameter anymore.
    (I don't know whether it's actually possible or not.)
    So I tried this:

    Code:
    public class Main extends JavaPlugin {
    
    public static Main plugin;
    
    public void onEnable(){
    plugin = this;
    }
    
    }
    This worked, but maybe there's a difference in ram usage or something?
    Can I do this? Or is it allowed to make a public static instance of Main class, but in another seperate class?

    Thank you in advance,
    Robnoo

    (Code by hard so there can be little mistakes in it)

    [Edit] Is there a way to add Java-colored code? I tried something I found (/CODE=java) but that doesn't work.
     
  2. Offline

    timtower Administrator Administrator Moderator

    @Robnoo It is [syntax=java]
    And go with the first one, the second one is very easy to make mistakes. Not to forget that static doesn't get cleaned by Bukkit.
    You never need static with Bukkit (or at all if you ask me)
     
  3. Offline

    Robnoo

    Thank you! I'll keep that in mind.

    Robnoo
     
  4. Offline

    The_Spaceman

    Code:
    public class Main extends JavaPlugin {
        public static Main getInstance() {
            return JavaPlugin.getPlugin(Main.class);
        }
    }
    I think this is the best way to get the instance of your main class.
    - its static
    - its not static stored
    - no constructor parameters
     
  5. Offline

    Robnoo

    @The_Spaceman
    Thank you for mentioning it! I think I'll use that future.

    Robnoo
     
Thread Status:
Not open for further replies.

Share This Page