Creating an instance in another class not being in the main class

Discussion in 'Spigot Plugin Development' started by Fazzer84, Jun 1, 2018.

  1. I want a HashMap that I did go to the event class.

    Code (Java):
    package net.FabricioSouza.construir;

    import java.util.HashMap;

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

    public class BuildCommands implements Listener,CommandExecutor {
       
        public static BuildCommands instance;
       
        public static HashMap<String, Construção> Build = new HashMap<>();
       
        public enum Construção{
            ON, OFF
        }
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String lb, String[] args) {
            if (!(sender instanceof Player)) {
                sender.sendMessage("§cEste comando apenas foi permitido para jogadores.");
            }
            Player p = (Player)sender;
            if (cmd.getName().equalsIgnoreCase("construir")) {
                if (p.hasPermission("build.mode")) {
                    if (args.length == 0) {
                        if (Build.get(p.getName()) == Construção.ON) {
                            Build.put(p.getName(), Construção.OFF);
                            p.sendMessage("§cSeu modo de construção foi desativado.");
                        } else {
                            Build.put(p.getName(), Construção.ON);
                            p.sendMessage("§aSeu modo de construção foi ativado.");
                        }
                    } else {
                        p.sendMessage("§cEste comando não possui argumentos para serem utilizados.");
                    }
                } else {
                    p.sendMessage("§cVocê precisa do grupo Construtor ou Superior para executar este comando.");  
                }
            }
            return false;
        }
    }
       
     
  2. Same problem, i'm forced to put everything in one class if I'm telling with arraylists or hashmaps D:
     
  3. Instance is a simple thing, but sometimes it needs a big code.
     
  4. I'm confused, what's the goal? You want to pass the hashmap you created to another class? Dependency injection.
     
  5. yes. Very well.
     
  6. Add the Map as a parameter to the constructor of BuildCommands; don't make the variable in BuildCommands static. Then, when you create an instance of BuildCommands in, for example, your class that extends JavaPlugin, pass your Map as an argument. This is the basic pattern of Dependency Injection (DI).

    Side note: It is generally wise to follow the principle "Program to interfaces, not implementations". Instead of storing a HashMap, store a Map. This is so you can provide a different implementation of the Map interface anytime you want different semantics than those of a HashMap (e.g., a ConcurrentHashMap), however, which still obey the contract defined in Map.

    Also, PLEASE never name variables upper-case (like Build)... it causes me, and I expect many others, physical pain.
     
    • Like Like x 1
  7. HOW I CREATE AN INSTANCE. PLEASE HELP ME.
     
  8. Your hashmap is the instance
     
  9. And how do I get the hashmap and put in another class.
     
  10. DavidDevelops

    Supporter

    EventClass events;

    //Access something from it
    events.myHashMap
    if im right this isn't a good way its just what i do for simple things

    So now you can access the hashmap with events.myHashMap, or anything else really,
     
  11. Please excuse me for being stupid. But post in code I'm bad.
     
  12. DavidDevelops

    Supporter

    What do you mean "post in code" it depends how you use it? Please learn basic java
    you put
    EventClass events;
    at the top
    You are using the class and creating a instance of it named events, then you use the instance to grab the hashmap out of it, Pretty simple..
     
    • Like Like x 1
    • Agree Agree x 1
  13. FrostedSnowman

    Resource Staff

    learn java
    you too
     
    • Funny Funny x 3
    • Like Like x 1
    • Winner Winner x 1
    • Friendly Friendly x 1
  14. In your class accessing another:
    Code (Java):
    private ClassWithMap c; //create null instance of your class
    public MyClass(ClassWithMap c) {
        this.main = main;
        //this passes the instance from the parameters to the null instance
    }
    In the class being accessed:
    Code (Java):
    public final MyClass c = new MyClass(this);
    //this passes the instance to the other class's constructor
    Then write a method that returns your HashMap (or, preferably, Map) in this class.
     
    • Agree Agree x 1
  15. Here it is...
     

    Attached Files:

    • 1.png
      1.png
      File size:
      145.1 KB
      Views:
      118
    • 2.png
      2.png
      File size:
      124.5 KB
      Views:
      107
  16. Why is this so stressful for everyone lol? He just wants to initialise his instance of BuildCommands does he not? So he could just do:

    Code (Java):
    package net.FabricioSouza.construir;

    import java.util.HashMap;

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

    public class BuildCommands implements Listener,CommandExecutor {
     
        public MainClass plugin;
     
        public HashMap<String, Construção> Build = new HashMap<>();
     
        public BuildCommands(MainClass plugin) {
          this.plugin = plugin;
        }

        public enum Construção{
            ON, OFF
        }
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String lb, String[] args) {
            if (!(sender instanceof Player)) {
                sender.sendMessage("§cEste comando apenas foi permitido para jogadores.");
            }
            Player p = (Player)sender;
            if (cmd.getName().equalsIgnoreCase("construir")) {
                if (p.hasPermission("build.mode")) {
                    if (args.length == 0) {
                        if (Build.get(p.getName()) == Construção.ON) {
                            Build.put(p.getName(), Construção.OFF);
                            p.sendMessage("§cSeu modo de construção foi desativado.");
                        } else {
                            Build.put(p.getName(), Construção.ON);
                            p.sendMessage("§aSeu modo de construção foi ativado.");
                        }
                    } else {
                        p.sendMessage("§cEste comando não possui argumentos para serem utilizados.");
                    }
                } else {
                    p.sendMessage("§cVocê precisa do grupo Construtor ou Superior para executar este comando.");
                }
            }
            return false;
        }
    }
       
    Code (Text):

    package com.test.blah;

    public class MainClass {
           private BuildCommands buildCmds;
           private static MainClass instance;

           public void onEnable() {
               instance = this;
               buildCmds = new BuildCommands(this);
           }

           public static MainClass getInstance() {
                   return instance;
           }
    }
     
    Now to access your hashmap of “Build” do MainClass.getInstance().buildCmds.Build

    Or is this not what he wanted?
     
    #16 ThatAbstractWolf, Jun 2, 2018
    Last edited: Jun 2, 2018
  17. I'm creating a / build plugin. As you see in the image I'm trying to put this "Build.put (p.getName (), Construção_OFF);" in another class to set "Construção_OFF" when the player enters.
     
  18. Then do what I said, it will work. Once you paste that code in I just made and you go to your onEnable method and do "new BuildCommands()" you can access BuildCommands.Build anywhere
     
  19. 1. Split your commands into another class implementing a CommandExecutor and register them onEnable. This is a very ugly way to do commands.

    2. You can either make a static reference to the BuildCommands within the BuildCommands itself or pass that instance of BuildCommands to your class that implements the CommandExecutor and store a local reference of BuildCommands with that instance of BuildCommands and call it from within the CommandExecutor Class

    3. Learn java before trying to build a plugin. Think of plugin development like this.

    Spigot/Bukkit Api are your materials and JAVA is your tools. You use these to build a plugin.

    If we apply this to lets say building a box out of wood.

    Wood is your materials and a hammer and nails are your tools. If you try to build the box without knowing how to use a hammer or nails you end up with a nail in your eye.

     
    #19 John_Willikers, Jun 2, 2018
    Last edited: Jun 2, 2018
    • Like Like x 1
    • Agree Agree x 1
    • Informative Informative x 1
  20. Please tell me the code in the instance that I have to put in the BuildCommands class and get the instance of this class to put in the BuildEvents class.