【发布时间】:2020-12-16 12:46:22
【问题描述】:
我有一个 Arraylist(从上游应用程序检索),其中包含大约 30 个值(计数不同)。我想根据 arraylist 中的值调用特定的方法。 例如:
List = {"a","b","c","d","e"}
如果 List 包含 "a" 我想执行 methodA ,同样适用于 "b" 等等。如果列表不包含"a",我不想运行methodA。
有没有有效的方法来解决这个问题?
【问题讨论】:
我有一个 Arraylist(从上游应用程序检索),其中包含大约 30 个值(计数不同)。我想根据 arraylist 中的值调用特定的方法。 例如:
List = {"a","b","c","d","e"}
如果 List 包含 "a" 我想执行 methodA ,同样适用于 "b" 等等。如果列表不包含"a",我不想运行methodA。
有没有有效的方法来解决这个问题?
【问题讨论】:
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));
【讨论】:
您可以使用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
【讨论】:
下面的截图是一个示例。 代码如下
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")
}
}
}
`
【讨论】: