参数化泛型的 XStream canConvert 问题
我有一个要求,我必须编写一个自定义 XStream MapConverter 来转换特定类型的地图。举个例子,我希望我的自定义转换器仅适用于 Map(String, Date) 地图。我需要通过重写 canConvert 方法来实现此目的。到目前为止,这是我编写的 canConvert 方法:
@Override
public boolean canConvert(Class clazz) {
return (!clazz.equals(Object.class) && Map.class.isAssignableFrom(clazz));
}
但这适用于所有类型的地图。由于“java.lang.Class”没有公开任何提供有关参数类型信息的方法,对于泛型集合,我无法在 canConvert 方法中实现所需的结果。
我能想到的一种解决方法是围绕 Map(String, Date) 创建一个虚拟包装类,并使用它来实现 canConvert 方法。有人可以建议在 canConvert 方法中解决此问题的更好方法吗?
I have a requirement where i have to write a custom XStream MapConverter that just converts a specific type of map. To give an example, i would want my custom converter to just work with Map(String, Date) maps. I need to achieve this by overriding the canConvert method. As of now, this is the canConvert method that i have written :
@Override
public boolean canConvert(Class clazz) {
return (!clazz.equals(Object.class) && Map.class.isAssignableFrom(clazz));
}
But this would work for all the type of maps. Since "java.lang.Class" does not expose any method that gives information about the type of parameters, for generic collections, i am unable to achieve the desired result in my canConvert method.
One workaround i could think is of creating a dummy wrapper class around Map(String, Date) and using that to implement the canConvert method. Could someone suggest a better way of tackling this issue in canConvert method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在这里对泛型做太多事情,因为它们在运行时不存在。您可以尝试获取第一个键和条目值并检查它们的类型。这显然不适用于空地图,但如果地图是空的,您可能无论如何都不需要转换它。
除此之外,就像您所说的那样,您几乎必须创建自己的包装类或推出仅接受 String 键和 Date 值的 Map 的自定义实现。
You can't do much with generics here since they're not present at runtime. You could try grabbing the first key and entry value and checking their types. This obviously wouldn't work for an empty map, but if a map is empty you probably don't need to convert it anyways.
Other than that it's like you say, you pretty much have to make your own wrapper class or roll a custom implementation of Map that only accepts String keys and Date values.