-1

I would like to store commands in a HashMap, but i cant access it from my main even when i have created an instanse of the object the HashMap is stored in.

interface Command{
    void execute(String[] args);
}

public class Register {
    private ArrayList<Obj> reg = new ArrayList<Obj>();
    private HashMap<String, Command> commands = new HashMap<String, Command>();

    protected void add(String[] cmd) {
        if(cmd.length>=4) {
            reg.add(new Obj(cmd[1]);
        }
    }
    
    
    public static void main(String args[]){
        Register a = new Register();
        Scanner read = new Scanner(System.in);
        
        a.commands.put("add", Register::add);
        
        while(true) {
            String line = read.nextLine();
            String cmd[] = line.split(" ");
            
            a.commands.get(cmd[0]).execute(cmd);
        }
        read.close();
    }
}

I'm using an class called register to store objects and i would like to access its functions through the console by adding a few functions to it, like "add abc" stores an object with the constructor Obj("abc"), but i cant add the commands into the hashmap because i cant access it through main.

1 Answers1

1

The problem is in a.commands.put("add", Register::add);

The main method is marked static, which means that it can only access other static methods. When you call Register::add, this is trying to say, "pass the method reference of the add method of the Register class" However, add is not a class (static) method, it is an instance method, so you have to denote which instance of Register you want to invoke it on.

You need to pass a specific instance of Register. For example, a::add will work in its place.

rb612
  • 5,280
  • 3
  • 30
  • 68
  • `Register::add` could also translate to `(Register r, String[] cmd) -> r.add(cmd)`, but that wouldn't fit the `Command` interface. – shmosel Oct 19 '21 at 00:47