【发布时间】:2011-10-23 19:25:51
【问题描述】:
也许标题措辞不好,知识渊博的人可以编辑它。
我想创建一个方法 parseFromJSONMap,它使用 gson 解析 JSON 文件并将数据作为 Map 返回,更具体地说是 Map<String, T>,其中 T 是名为 Entity 的类的子类。到目前为止已经定义了两个子类,Creature 和 Hero,但以后可能会有更多。所以如果我打电话给
parseFromJSONMap(file, Creature.class)
它应该返回一个Map<String, Creature> 如果我打电话
parseFromJSONMap(file, Hero.class)
它应该返回一个Map<String, Hero> 等。
这就是这个方法现在的样子(它只适用于生物):
public static <T extends Entity> Map<String, T> parseFromJSONMap(File file, Class<T> clazz) throws FileNotFoundException
{
Type type = new TypeToken<HashMap<String, Creature>>(){}.getType();
return gson.fromJson(new FileReader(file), type);
}
所以我想输入T,而不是Creature。如果我这样做并这样称呼它
Map<String, Creature> test = Entity.parseFromJSONMap(somefile, Creature.class);
我收到java.lang.Object cannot be cast to heroes.model.Creature
我想要的可能吗?
编辑:当我在test 上调用任何方法时发生异常,例如test.get("someCreature"),所以这是一个运行时异常。
【问题讨论】:
-
可能值得添加您获得的堆栈跟踪
-
我认为这是我得到的唯一例外,因为我所拥有的只是
Creature中调用Entity.parseFromJSONMap的临时 main 方法。Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to heroes.model.Creature at heroes.model.Creature.main(Creature.java:131)