我有一个完整的stumper,并将其提供给所有人,看看你是否知道发生了什么事情。未能强制在Java通用类型
这是数据结构
Map<String, Object> objectMap
它存储字符串和数值现在,但可能在未来存储更多类型。
这是我用来检索这些值的函数:
public <T> T get(String variable, T defaultValue) {
// returns either the object from the map, or the default if its not in the map.
Object value = getObject(variable, defaultValue);
logger.debug("default value is of type " + defaultValue.getClass().getName());
// Attempt to get around casting issue
if (value instanceof Number)
{
value = (Number) value;
}
T ret = (T) value;
logger.debug("Variable " + variable + " which is of type " + value.getClass().getName() + " and returning as " + ret.getClass().getName() + " (is number: " + (value instanceof Number) + ")");
return ret;
}
这是调用代码:
public int getFoo() { return this.<Integer>get("foo", 0); }
这是输出我在日志中看到:
default value is of type java.lang.Integer
Variable foo which is of type java.lang.Long and returning as java.lang.Long (is number: true)
就在它失败之前:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
这里最让我担心的是类的类型看起来很长,尽管试图强制类使用Integer。
我错过了什么,或者违反了Java泛型的一些概念?
感谢所有帮助
对于初学者,你真的不应该使用'Map'。地图应该有一个单一的,具体的价值类型,它真的是有代码的臭混合在一起。 –
2012-03-05 08:14:02
请发送更多堆栈跟踪,发生此异常? – MJM 2012-03-05 08:18:40
对地图的看法是什么? – 2012-03-05 08:19:21