我有一个带有一些值的HashMap
。我想迭代映射中的每个值,并为每个值调用一个方法 myFun()
。
myFun()
是一个重载方法,它有两个参数:一个是 String,另一个可以是 Integer、Decimal、Float、String、String[]、Value、Value[] 等类型:
Map<String, Object> NodesFound = new HashMap<>();
String[] children = {"child1","child2","child3","child4"};
NodesFound.put("String", "Hi its a string");
NodesFound.put("Number", 1);
NodesFound.put("children", children);
Set<String> nodeLabels = NodesFound.keySet();
for (String label : nodeLabels) {
Object value = NodesFound.get(label);
Class<?> theClass = value.getClass();
myFun("myVal", theClass.cast(value))
}
预期:myFun()
不应给出类型不匹配错误。
实际: 出现以下编译错误: Node 类型中的方法 myFun(String, Value) 不适用于参数 (String, 捕获#3-of ?)
最佳答案
使用cast
,您需要theClass
要使用非通配符类型参数(例如 Class<String>
)声明的变量,如果它要引用不同基础类型的类,则不能这样做。
它很丑,但我认为你无法避免instanceof
在这里,这可能意味着值得重新审视为什么同一张 map 中有各种不同的类型。
但是如果您要这样做,那么:
if (value instanceof Integer) {
myFun("myVal", (Integer)value);
} else if (value instanceof String) {
myFun("myVal", (String)value);
} else if (value instanceof ...) {
// ...
} else {
throw new AppropriateException();
}
不过,类似的链式店再次建议您重新考虑 NodesFound
.
关于java - 如何动态确定 Object 类型文字的实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913554/