Use of classes

Discussion in 'Plugin Development' started by Spysical, May 9, 2012.

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

    Spysical

    I've been trying to use classes in my plugin.

    It doesn't do much. But it's enough.
    Every time it goes wrong when it has to use the method of another class.
    If I must I can post the rest of my code too.
    The Command Listener is under here.
    PHP:
    package net.nijholt.bukkitpluginmax;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
     
    /**
    *
    * @author Spysical aka Max Nijholt
    *
    */
    public class BPMWarExecutor implements CommandExecutor {
     
        private 
    BukkitPluginMax plugin;
        private static 
    BPMWarBasic war;
     
        
    BPMWarExecutor(BukkitPluginMax plugin) {
            
    this.plugin plugin;
        }
     
        public 
    boolean onCommand(CommandSender csCommand cmdString aliasString[] args) {
            
    // Als het command war is.
            
    if (cmd.getName().equalsIgnoreCase("war")) {
                
    // en er geen argumenten zijn, laat dan help zien
                
    if (args.length == 0) {
                    
    cs.sendMessage(ChatColor.GREEN "BPM War help:");
                    
    cs.sendMessage(ChatColor.RED "/war join [team]" ChatColor.GREEN "...");
                    
    cs.sendMessage(ChatColor.RED "/war leave" ChatColor.GREEN "...");
                    
    cs.sendMessage(ChatColor.RED "/war kick" ChatColor.GREEN "...");
                    
    cs.sendMessage(ChatColor.RED "/war set [setting]" ChatColor.GREEN "...");
                    return 
    true;
                }
                
    // Als de caster een instance van Player is.
                
    if (cs instanceof Player) {
                    
    Player player = (Playercs;
                    
    // Er argumenten zijn
                    
    if (args.length >= 1) {
                        
    // en het command /war join is
                        
    if (args[0].equalsIgnoreCase("join")) {
                            
    // Bij geen argumenten, random joinen van een team.
                            
    if (args.length == 1) {
                                if ((
    plugin.perms.has(cs"BukkitPluginMax.war.join") || plugin.perms.has(cs"BukkitPluginMax.war.*") || plugin.perms.has(cs"BukkitPluginMax.war.join.*")) || player.isOp()) {
                                    
    war.RandomTeamJoin(player);
                                } else {
                                    
    // Als der geen permissies hiervoor zijn. Dan geeft dit dat aan bij de speler.
                                    
    player.sendMessage(ChatColor.RED "Sorry you have no permissons to do that!");
                                    return 
    true;
                                }
                            }
                            
    // Als er wel aan wordt gegeven in welk team die wil.
                            
    if (args.length && args.length 3) {
                                if ((
    plugin.perms.has(cs"BukkitPluginMax.war.join.team") || plugin.perms.has(cs"BukkitPluginMax.war.*") || plugin.perms.has(cs"BukkitPluginMax.war.join.*")) || player.isOp()) {
                                    
    // Als het argument blue is. Komt die bij team blue, en het zelfde geld voor rood.
                                    
    if (args[1].equalsIgnoreCase("blue")) {
                                        
    war.JoinTeamBlue(player);
                                    } else if (
    args[1].equalsIgnoreCase("red")) {
                                        
    war.JoinTeamRed(player);
                                    }
                                } else {
                                    
    // Als der geen permissies hiervoor zijn. Dan geeft dit dat aan bij de speler.
                                    
    player.sendMessage(ChatColor.RED "Sorry you have no permissons to do that!");
                                    return 
    true;
                                }
                            } else if (
    args.length >= 3) {
                                
    cs.sendMessage(ChatColor.RED "Too many arguments!");
                                return 
    true;
                            }
                        } else if ((
    args[0].equalsIgnoreCase("leave") || args[0].equalsIgnoreCase("leaveteam")) && (plugin.perms.has(cs"BukkitPluginMax.war.leave") || plugin.perms.has(cs"BukkitPluginMax.war.*"))) {
                            
    // Het verlaten van je team onder voorwaarde dat je daar permissies voor hebt.
                            
    war.leaveTeam(player);
                        } else if (
    args[0].equalsIgnoreCase("kick")) {
                            if (
    plugin.perms.has(cs"BukkitPluginMax.war.kick") || player.isOp()) {
                                if (
    args.length == 2) {
                                    
    Player other = (Bukkit.getServer().getPlayer(args[1]));
                                    if (
    other == null) {
                                        
    cs.sendMessage(ChatColor.RED args[1] + " is not online!");
                                        return 
    false;
                                    } else if (
    other != null) {
                                        
    war.leaveTeam(other);
                                        
    Bukkit.broadcastMessage(other " got kicked from his team.");
                                    }
                                    return 
    false;
                                }
                                if (
    args.length 2) {
                                    
    cs.sendMessage(ChatColor.RED "Too many arguments!");
                                }
                            }
                        } else if (
    args[0].equalsIgnoreCase("set")) {
                            if (
    plugin.perms.has(cs"BukkitPluginMax.war.set")) {
                                if (
    args.length == 1) {
                                    
    cs.sendMessage(ChatColor.GREEN "BPM War" ChatColor.RED " /war set" ChatColor.GREEN " help:");
                                    
    cs.sendMessage(ChatColor.RED "/war set [setting]" ChatColor.GREEN "...");
                                    
    cs.sendMessage(ChatColor.GREEN "Settings:");
                                    
    cs.sendMessage(ChatColor.BLUE "Hardcore");
                                } else if (
    args.length == 2) {
                                    if (
    args[1].equalsIgnoreCase("hardcore")) {
                                        
    war.setHardcoreONOFF(player);
                                    }
                                } else if (
    args.length == 3) {
                                    if (
    args[2].equalsIgnoreCase("on")) {
                                        
    war.setHardcoreON(player);
                                    } else if (
    args[2].equalsIgnoreCase("off")) {
                                        
    war.setHardcoreOFF(player);
                                    } else {
                                        
    cs.sendMessage(ChatColor.RED "You've entered an invallid argument.");
                                    }
                                }
                            }
                        }
                    }
                } else{
                    
    cs.sendMessage("Only Players can execute commands");
                }
            }
            return 
    true;
        }
    }
    Sorry for the dutch comments in the code. Teacher wants to understand it too :p

    Thank you very much for even opening this thread :D
     
  2. Offline

    Father Of Time

    Unfortunately this is far too much code for me to parse through with the time I have, can you post just the function call and the initialization of the class for review?

    Also, on a side note try not using nested if statements as much, they are messy and hard to read; when possible try using else if statements.

    Generally when using classes I create an instance of the class in the main plug-in class, then create a getter for that class object; then when ever I need to use a function in that class I call the plugin main class, call the getter for the custom class to get the instance of the class then call the function from that instance.
     
  3. Offline

    Spysical

    Thanks you very much, but I don't know exactly how I should do that. Could you give me an example?
    I'm quite new into developing plugins.

    My "war" class

    PHP:
    package net.nijholt.bukkitpluginmax;
     
    import java.util.HashSet;
    import java.util.Set;
    import org.bukkit.entity.Player;
     
    /**
    *
    * @author Spysical aka Max Nijholt
    *
    */
     
    public class BPMWarBasic {
        
    // Sets aan maken voor de teams
        
    private Set<PlayerTeamRed = new HashSet<Player>();
        private 
    Set<PlayerTeamBlue = new HashSet<Player>();
        private 
    BukkitPluginMax plugin;
     
        
    BPMWarBasic(BukkitPluginMax plugin) {
            
    this.plugin plugin;
        }
        
    // het aan en uit zetten van hardcore
        
    public void setHardcoreONOFF(Player cs){
            if(
    plugin.Hardcore){
                
    setHardcoreOFF(cs);
                
    cs.sendMessage("Hardcore is now disabled");
            }else if(!
    plugin.Hardcore){
                
    setHardcoreON(cs);
                
    cs.sendMessage("Hardcore is now enabled");
            }
        }
       
        public 
    void setHardcoreON(Player cs){
            
    plugin.Hardcore true;
        } 
       
        public 
    void setHardcoreOFF(Player cs){
            
    plugin.Hardcore false;
        }   
       
        
    // Opzoeken van de grote van team rood
        
    int getTeamRedSize() {
            return 
    TeamRed.size();
        }
     
        
    // Opzoeken van de grote van team blauw
        
    int getTeamBlueSize() {
            return 
    TeamBlue.size();
        }
     
        
    // Opzoeken of een speler in team rood zit
        
    public boolean inTeamRed(Player player) {
            return 
    TeamRed.contains(player);
        }
     
        
    // Opzoeken of een speler in team blauw zit
        
    public boolean inTeamBlue(Player player) {
            return 
    TeamBlue.contains(player);
        }
     
        
    // het random joinen van een team. Waar die als default blue als eerste vult.
        
    public void RandomTeamJoin(Player player) {
            if (
    getTeamBlueSize() <= getTeamRedSize()) {
                if (!
    inTeamBlue(player) || inTeamRed(player)) {
                    
    TeamBlue.add(player);
                    
    player.sendMessage("You've joined team blue");
                }
            }
            if (
    getTeamBlueSize() > getTeamRedSize()) {
                if (
    inTeamBlue(player) || !inTeamRed(player)) {
                    
    TeamRed.add(player);
                    
    player.sendMessage("You've joined team red");
                }
            }
        }
     
        
    // Team blue joinen
        
    public void JoinTeamBlue(Player player) {
            if (!
    inTeamBlue(player)) {
                
    TeamBlue.add(player);
                
    player.sendMessage("You've joined team blue");
            }
        }
     
        
    // team rood joinen
        
    public void JoinTeamRed(Player player) {
            if (!
    inTeamRed(player)) {
                
    TeamRed.add(player);
                
    player.sendMessage("You've joined team red");
            }
        }
     
        
    // het verlaten van je team
        
    public void leaveTeam(Player player) {
            if (
    inTeamBlue(player)) {
                
    TeamBlue.remove(player);
                
    player.sendMessage("You've left team blue");
            }
            if (
    inTeamRed(player)) {
                
    TeamRed.remove(player);
                
    player.sendMessage("You've left team red");
            }
            if (!
    inTeamBlue(player) && !inTeamRed(player)){
                
    player.sendMessage("You were not in any team");
            }
        }
       
        
    // Check of ze in t zelfde team zitten
        
    public boolean inSameTeam(Player playerPlayer target) {
            
    boolean dmg true;
            if (!
    plugin.Hardcore) {
                if (
    inTeamBlue(player) && inTeamBlue(target)) {
                    
    dmg false;
                } else if (
    inTeamRed(player) && inTeamRed(target)) {
                    
    dmg false;
                }
            }
            return 
    dmg;
        }
    }
     
  4. Offline

    CorrieKay

    For example, if you had a class file called "CustomClass" and you wanted to create a getter for it in your main class, in the main class, you would put:

    private CustomClass className = new CustomClass(parametershere);

    Then you need a getter method,

    public CustomClass getCustomClass(){
    return className;
    }

    then you would use your main class to call that method, and there you have your object!

    Another way you may wish to do this, is by setting your main class as a static variable, so you can call it from anywhere you want

    For instance, alongside your custom object, you would put
    public static Main instance;

    In onEnable:
    instance = this;

    So then you can just do

    Main.instance.getCustomClass()

    to get your custom class without having to pass your instance around everywhere :p
     
    Spysical likes this.
  5. Offline

    Father Of Time

    So with your example if I wanted to create an instance in my main class to use for the duration the plug-in is running I would do the following:

    Code:
        private final static BPMWarBasic WarBasicHandler = new BPMWarBasic( this );
    
    Then to get this instance from any class we can create a static getter:

    Code:
        public static BPMWarBasic getBPMWarBasic()
        {
            return WarBasicHandler;
        }
    
    So then any time you need to use a function inside your custom class you simply get the instance from the main class using the static getter. So for instance, if you wanted to use the getTeamRedSize() function in your BPMWarBasic class, you would:

    Code:
    <MAINCLASSNAME>.getBPMWarBasic().getTeamRedSize();
    
    replacing <MAINCLASSNAME> with what ever the name of your main class is that has the static final variable stored in it.

    I should note that this is far from the only way to achieve this, but I often find this to be a great solution to working with classes that are being used as handlers.

    I hope this helps clear things up a little, good luck with your project!
     
    Spysical likes this.
  6. Offline

    Spysical

    It now tells me "non-static variable this can not be referenced from a static context"
    Any way to fix this?
     
  7. Offline

    Father Of Time

    static means (simplifying of coarse) that there is only one instance of that object shared across all classes, so if you have:

    Code:
    Integer test;
    In a class each instance of the class will have its own value, so one may be set to 6, another 9, etc.

    However, if you do the following:

    Code:
    static Integer test;
    then every instance of your class shares the same value, so if you do:

    Code:
    test = 9;
    then every single instance of that class will have test set to 9.

    So seeing as static variables have the same value regardless of what instance they reside in they can be accessed from any class.

    So more specific to your issue, the reason you are getting this error is because you are trying to access a variable directly in a class as if it was static without actually declaring it static. You either forgot to make the getter function static or the variable itself, but without code to review that is only an assumption.

    Show us where you declare your class and your getter, likely we can resolve it by reviewing those two sections of code.
     
  8. Offline

    Double0negative

    That error means that you have a static method and your trying to access a non-static variable. You need to make the variable static too
     
  9. Offline

    Spysical

    Leaving out the non essential parts of code,
    PHP:
    public class BukkitPluginMax extends JavaPlugin {
     
        public final 
    BPMBlockListener bl = new BPMBlockListener(this);
        public final 
    BPMEntityListener el = new BPMEntityListener(this);
        public final 
    BPMPlayerListener pl = new BPMPlayerListener(this);
    // this is where i get the error.   
    private final static BPMWarBasic WarBasicHandler = new BPMWarBasicthis );
        private 
    BPMCommandExecutor Executor;
        private 
    BPMWarExecutor Executor2;
        private 
    BPMEcoCommands Executor3;
        private 
    BPMEconomyBasic eco;
        private 
    Set<Playercarpets = new HashSet<Player>();
        private 
    Map<PlayerLinkedList<BlockState>> blocks = new HashMap<PlayerLinkedList<BlockState>>();
        private 
    Set<Playerwatch = new HashSet<Player>();
        
    int CarpetLength;
        
    double TeamKillMoney;
        
    double LoginBonus;
        
    boolean LoginBonusing;
        
    Logger log;
        private static 
    Vault vault null;
        public static 
    Economy econ null;
        public static 
    Permission perms null;
        public static 
    Chat chat null;
        public 
    boolean Hardcore;
        public static 
    BukkitPluginMax instance;
       
        public static 
    BPMWarBasic getBPMWarBasic()    {
            return 
    WarBasicHandler;
        }
     
       
        public 
    void onDisable() {
            
    // TODO: Place any custom disable code here.
            
    log.info(this " is now disabled!");
        }
     
        public 
    void onEnable() {
            
    // TODO: Place any custom enable code here, such as registering events
            
    log this.getLogger();
            
    Plugin x this.getServer().getPluginManager().getPlugin("Vault");
            if (
    != null instanceof Vault) {
                
    vault = (Vaultx;
                
    log.info("Hooked succesfully");
                
    //log.info(String.format("[%s] Hooked %s %s", getDescription().getName(), vault.getDescription().getName(), vault.getDescription().getVersion()));
            
    } else {
                
    //log.warning(String.format("[%s] Vault was _NOT_ found! Disabling BukkitPluginMax.instance.", getDescription().getName()));
                
    getPluginLoader().disablePlugin(this);
                
    log.info("Disabling");
                return;
            }
            
    PluginManager pm getServer().getPluginManager();
            
    pm.registerEvents(plthis);
            
    pm.registerEvents(blthis);
            
    pm.registerEvents(elthis);
            
    this.getConfig().options().copyDefaults(true);
            
    saveConfig();
            
    instance this;
            
    CarpetLength getConfig().getInt("fun.Length");
            if (
    CarpetLength == 0) {
                
    CarpetLength 5;
            }
            
    TeamKillMoney getConfig().getDouble("Economy.remove.TeamKillMoney");
            
    LoginBonus getConfig().getDouble("Economy.loginbonus.amount");
            
    LoginBonusing getConfig().getBoolean("Economy.loginbonus.enable");
            
    Hardcore getConfig().getBoolean("War.settings.Hardcore");
            
    log.info(this " is now enabled!");
            
    log.info("======Settings=======");
            
    log.info("Carpet length = " CarpetLength);
            
    log.info("PvP teamkill = " TeamKillMoney);
            
    Executor = new BPMCommandExecutor(this);
            
    Executor2 = new BPMWarExecutor(this);
            
    Executor3 = new BPMEcoCommands(this);
            
    getCommand("bpm").setExecutor(Executor);
            
    getCommand("war").setExecutor(Executor2);
            
    getCommand("eco").setExecutor(Executor3);
            
    setupPermissions();
            
    setupEconomy();
            
    //setupChat();
        
    }
    and
    PHP:
    public class BPMWarBasic {
        
    // Sets aan maken voor de teams
        
    private Set<PlayerTeamRed = new HashSet<Player>();
        private 
    Set<PlayerTeamBlue = new HashSet<Player>();
        private 
    BukkitPluginMax plugin;
     
        
    BPMWarBasic(BukkitPluginMax plugin) {
            
    this.plugin plugin;
        }
          
     
  10. Offline

    Father Of Time

    Hello once more,

    I don’t believe you can use the “this” variable during initialization. If you wish to use the following:

    Code:
    private final static BPMWarBasic WarBasicHandler = new BPMWarBasic( this );
    
    You would need to change it to this:
    Code:
    private final static BPMWarBasic WarBasicHandler;
    
    Then inside your onEnable() function add the following:

    Code:
    WarBasicHandler = new BPMWarBasic( this );
    
    Because the onEnable() function happens after the server compiles, meaning the “this” variable will return the class it resides in, while during compile it will return null.

    I can’t say for sure whether this is your problem or not, but I think it will cause issues if I remember correctly. Oh that and you can’t use “this” when declaring a static variable because static is a global object reference, where this is a single object reference.

    Give this a shot and see what errors, if any, come next. :D
     
Thread Status:
Not open for further replies.

Share This Page