如何调用存储在HashMap中的方法? (JAVA) [英] How to call a method stored in a HashMap? (Java)

查看:140
本文介绍了如何调用存储在HashMap中的方法? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户将在命令行/终端Java程序中输入的命令列表(i,h,t等)。我想存储一个命令/方法对的散列:

I have a list of commands (i, h, t, etc) that the user will be entering on a command line/terminal Java program. I would like to store a hash of command/method pairs:

'h', showHelp()
't', teleport()

这样我就可以得到如下代码:

So that I can have code something like:

HashMap cmdList = new HashMap();

cmdList.put('h', showHelp());
if(!cmdList.containsKey('h'))
    System.out.print("No such command.")
else
   cmdList.getValue('h')   // This should run showHelp().

这可能吗?如果没有,那么简单的方法是什么?

Is this possible? If not, what is an easy way to this?

推荐答案

使用Java 8+和Lambda表达式



使用lambdas(Java 8+中可用),我们可以这样做:

With Java 8+ and Lambda expressions

With lambdas (available in Java 8+) we can do it as follows:

class Test {

    public static void main(String[] args) throws Exception {
        Map<Character, Runnable> commands = new HashMap<>();

        // Populate commands map
        commands.put('h', () -> System.out.println("Help"));
        commands.put('t', () -> System.out.println("Teleport"));

        // Invoke some command
        char cmd = 't';
        commands.get(cmd).run();   // Prints "Teleport"
    }
}

在这种情况下,我是懒惰并且重用了 Runnable 接口,但是我们也可以使用我在Java中发明的 Command 接口7的版本的答案。

In this case I was lazy and reused the Runnable interface, but one could just as well use the Command-interface that I invented in the Java 7 version of the answer.

此外,还有() - > {...} 语法。您可以使用 help teleport 的成员函数,并使用 YourClass :: help resp。 YourClass :: teleport 取而代之。

Also, there are alternatives to the () -> { ... } syntax. You could just as well have member functions for help and teleport and use YourClass::help resp. YourClass::teleport instead.


  • http://programming.guide/java/lambda-cheat-sheet.html =noreferrer> Lambda备忘单在Programming.Guide上。

  • A great Lambda cheat sheet over at Programming.Guide.

Oracle教程在这里: Java教程™ &ndash的; Lambda Expressions

Oracle tutorial here: The Java Tutorials™ – Lambda Expressions.

你真正想做的是创建一个接口,命名为 Command (或者重用例如 Runnable ),让你的映射的类型为 Map< Character,Command> 。像这样:

What you really want to do is to create an interface, named for instance Command (or reuse for instance Runnable), and let your map be of the type Map<Character, Command>. Like this:

import java.util.*;

interface Command {
    void runCommand();
}

public class Test {

    public static void main(String[] args) throws Exception {
        Map<Character, Command> methodMap = new HashMap<Character, Command>();

        methodMap.put('h', new Command() {
            public void runCommand() { System.out.println("help"); };
        });

        methodMap.put('t', new Command() {
            public void runCommand() { System.out.println("teleport"); };
        });

        char cmd = 'h';
        methodMap.get(cmd).runCommand();  // prints "Help"

        cmd = 't';
        methodMap.get(cmd).runCommand();  // prints "teleport"

    }
}



反射hack



有了这个说法,你可以真正做你想要的东西(使用反射和方法 class。)

import java.lang.reflect.*;
import java.util.*;

public class Test {

    public static void main(String[] args) throws Exception {
        Map<Character, Method> methodMap = new HashMap<Character, Method>();

        methodMap.put('h', Test.class.getMethod("showHelp"));
        methodMap.put('t', Test.class.getMethod("teleport"));

        char cmd = 'h';
        methodMap.get(cmd).invoke(null);  // prints "Help"

        cmd = 't';
        methodMap.get(cmd).invoke(null);  // prints "teleport"

    }

    public static void showHelp() {
        System.out.println("Help");
    }

    public static void teleport() {
        System.out.println("teleport");
    }
}

这篇关于如何调用存储在HashMap中的方法? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆