【问题标题】:Call specific method based on the ArrayList value in javajava中根据ArrayList值调用具体方法
【发布时间】:2020-12-16 12:46:22
【问题描述】:

我有一个 Arraylist(从上游应用程序检索),其中包含大约 30 个值(计数不同)。我想根据 arraylist 中的值调用特定的方法。 例如:

List = {"a","b","c","d","e"}

如果 List 包含 "a" 我想执行 methodA ,同样适用于 "b" 等等。如果列表不包含"a",我不想运行methodA

有没有有效的方法来解决这个问题?

【问题讨论】:

    标签: java arraylist


    【解决方案1】:
        List<String> list = List.of("a", "b", "c", "d", "e");
    
        Map<String, Consumer> ACTIONS = Map.of(
                "a", v -> System.out.println("A"),
                "b", v -> System.out.println("B"),
                "c", v -> System.out.println("C"),
                "d", v -> System.out.println("D"),
                "e", v -> System.out.println("E")
        );
    
        list.forEach(e -> ACTIONS.get(e).accept(e));
    

    【讨论】:

      【解决方案2】:

      您可以使用Java Reflection,它允许您在运行时获取有关类、方法、字段等的动态信息。

      实现上述方法的代码:

      import java.util.*;
      
      public class StackOverflow {
          private static class Target {
              public void methodA() {
                  System.err.println("methodA");
              }
      
              public void methodB() {
                  System.err.println("methodB");
              }
      
              public void methodC() {
                  System.err.println("methodC");
              }
          }
      
          public static void main(String[] args) throws Exception {
              Target target = new Target();
              ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[] { "a", "c" }));
              for (String item : list) {
                  target.getClass().getMethod("method" + item.toUpperCase()).invoke(target, new Object[0]);
              }
          }
      }
      

      输出:

      $ javac StackOverflow.java && java StackOverflow
      methodA
      methodC
      

      【讨论】:

        【解决方案3】:

        下面的截图是一个示例。 代码如下

          static void main(String[] args){
            def yourList = ["a","b","c"]
        
            //my way of test data
            String sample = "{\"a\" : \"Do action of A\", \"b\":\"Do action of B\"}"
            yourList.each {String value ->
        
                Map testData = (Map) new JsonSlurper().parseText(sample)
                if(testData.containsKey(value)){
                    println(testData.get(value))
                }else {
                    println("not found")
        
                }
        
            }
        }
        

        `

        【讨论】:

          猜你喜欢
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 2013-08-28
          • 2014-02-14
          • 2020-02-18
          • 2011-08-24
          • 2017-08-02
          • 1970-01-01
          相关资源
          最近更新 更多