Java 如何动态确定对象类型的文本的实际类型
我有一个带有一些值的Java 如何动态确定对象类型的文本的实际类型,java,casting,Java,Casting,我有一个带有一些值的HashMap。我想迭代映射中的每个值,并为每个值调用一个方法myFun() myFun()是一个重载方法,它有两个参数:一个是String,另一个可以是Integer、Decimal、Float、String、String[],Value、Value[]等类型: Map<String, Object> NodesFound = new HashMap<>(); String[] children = {"child1","child2
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))
}
Map NodesFound=new HashMap();
字符串[]children={“child1”、“child2”、“child3”、“child4”};
NodesFound.put(“String”,“Hi is a String”);
NodesFound.put(“数字”,1);
NodesFound.put(“children”,children);
Set nodeLabels=NodesFound.keySet();
用于(字符串标签:节点标签){
对象值=NodesFound.get(标签);
Class theClass=value.getClass();
myFun(“myVal”,class.cast(值))
}
应为:myFun()
不应给出类型不匹配错误
实际:
将出现以下编译错误:
类型节点中的方法myFun(字符串,值)不适用于参数(字符串,
capture#3-of?要使用
cast
,您需要使用非通配符类型参数声明theClass
变量(例如,Class
),如果它要引用不同底层类型的类,则不能这样做
这很难看,但我不认为您可以在这里避免instanceof
,这可能意味着值得再次探讨为什么在同一个地图中有各种不同的类型
但如果你要这么做,那么:
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
这是行不通的
编译器在编译时决定选择哪个重载方法
您不能将其“推迟”到运行时
实现这一目标的唯一方法是:
- 对所有不同的情况使用instanceof和静态强制转换
- 尝试设计一个使用覆盖的解决方案,就像在运行时那样(但可能需要完全不同的设计)
int
。读了这个问题,我不明白为什么…:-)谢谢