Search code examples
staticbukkitnon-static

Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin


I am trying to create a Minecraft plugin with a command that will set the world name into config.yml. Except I keep getting "Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin" when I attempt to set the config. I have already searched around for several way to fix this but I have not understood have to implement other situations into mine.

Here is my code:

Main.java:

package me.Liam22840.MurderRun;

import org.bukkit.plugin.java.JavaPlugin;

import me.Liam22840.MurderRun.commands.HelpCommand;
import me.Liam22840.MurderRun.commands.SetmapCommand;

public class Main extends JavaPlugin {

@Override
public void onEnable(){
    loadConfig();
    new HelpCommand(this);
    new SetmapCommand(this);
}   

public void loadConfig(){
    getConfig().options().copyDefaults(true);
    saveConfig();
    }
}

SetmapCommand.java:

package me.Liam22840.MurderRun.commands;

import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;

import Utils.Utils;
import me.Liam22840.MurderRun.Main;
import me.Liam22840.MurderRun.getConfig;


public class SetmapCommand implements CommandExecutor{
   private int count;
   public SetmapCommand(Main plugin){
       plugin.getCommand("Setmap").setExecutor(this);

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (!(sender instanceof Player)){
        sender.sendMessage("Only players can execute this command!");
        return true;
    }
    Player p = (Player) sender; 
    Location b_loc = p.getLocation();
    if(p.hasPermission("MurderRun.Setworld")){
        Main.getConfig().set("Maps." + p.getName() + count + ".World", b_loc.getWorld().getName());
        Main.saveConfig();
        p.sendMessage(Utils.chat("&4Map Set"));
        return true;
    } else{
        p.sendMessage("You do not have the required permissions to execute this command!");             
    }
    return false;

    }

}

Solution

  • You can't directly call the Main class, because it is not static. To call it, you should do this in your Setmap class and the constructor:

    private Main plugin;
    
    public SetmapCommand(Main plugin){
       this.plugin = plugin;
       plugin.getCommand("Setmap").setExecutor(this);
    }
    

    After you did this, you can use in your Setmap class: plugin.saveConfig();