开发者社区 问答 正文

java如何遍历执行方法

伪代码:

for(String key, map.keyset()) {
    if(map.get(key) != null) {
        obj.key?();
    }
}

上面的key?代表根据不同的key执行不同的方法,比如key为"key1"时 obj.key1(),key为"key2"时,obj.key2()
问:java如何实现?

展开
收起
蛮大人123 2016-03-06 10:09:26 2045 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    需要使用反射:

    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.*;
    
    public class ReflectionDemo {
    
        public void a(String param) {
            System.out.println("do one thing: " + param );
        }
    
        public void b(String param) {
            System.out.println("do another thing: " + param);
        }
    
        public static void main(String[] args) {
            ReflectionDemo reflectionDemo = new ReflectionDemo();
            Map<String, String> methods = new HashMap<String, String>();
            methods.put("a", "someData");
            methods.put("b", "anotherData");
    
            for (Map.Entry<String, String> item : methods.entrySet()) {
                try {
                    //getMethod第一个参数是函数名,后面的参数都是针对于目标方法的参数类型,没有参数就传null
                    Method method = ReflectionDemo.class.getMethod(item.getKey(), String.class);
                    //invoke第一个参数是一个对象的实例,后面跟进一堆参数列表,没有参数就传null
                    method.invoke(reflectionDemo, item.getValue());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }

    输出
    `
    do one thing: someData
    do another thing: anotherData
    `

    2019-07-17 18:54:07
    赞同 展开评论
问答分类:
问答地址: