栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java 如何调用存储在HashMap中的方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 如何调用存储在HashMap中的方法?

使用Java 8+和Lambda表达式
使用lambda(可在Java 8+中使用)进行以下操作:

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
接口,但是也可以使用
Command
我在答案的Java 7版本中发明的-
interface

此外,

() -> { ... }
语法还有其他选择。你也可以具有和的成员函数help,
teleport
并使用
YourClass::helpresp
YourClass::teleport
代替。

  • Programming.Guide上有一篇很棒的Lambda备忘单。
  • 此处的Oracle教程:Java教程™– Lambda表达式。

Java 7及以下
你真正想要做的是创建一个接口Command(例如命名)(或例如重用Runnable),然后让你的地图成为type Map。像这样:

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"    }}Reflection "hack"

话虽如此,你实际上可以完成你所要的工作(使用反射和

Method
类)。

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");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506635.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号