参数化泛型的 XStream canConvert 问题

发布于 2024-10-31 18:38:25 字数 531 浏览 6 评论 0原文

我有一个要求,我必须编写一个自定义 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清浅ˋ旧时光 2024-11-07 18:38:25

您不能在这里对泛型做太多事情,因为它们在运行时不存在。您可以尝试获取第一个键和条目值并检查它们的类型。这显然不适用于空地图,但如果地图是空的,您可能无论如何都不需要转换它。

Map<String, Date> m = new HashMap<String, Date>();
m.put("test", new Date());
Object key = m.keySet().iterator().next();
Object value = m.get(key);

System.out.println(key.getClass().isAssignableFrom(String.class));
System.out.println(value.getClass().isAssignableFrom(Date.class));

除此之外,就像您所说的那样,您几乎必须创建自己的包装类或推出仅接受 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.

Map<String, Date> m = new HashMap<String, Date>();
m.put("test", new Date());
Object key = m.keySet().iterator().next();
Object value = m.get(key);

System.out.println(key.getClass().isAssignableFrom(String.class));
System.out.println(value.getClass().isAssignableFrom(Date.class));

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文