【发布时间】:2014-06-19 05:32:34
【问题描述】:
我正在编写需要在 c# 和 java 上工作的对象序列化器/反序列化器类。我在下面的 c# 部分处理了这个问题:
Type listType = typeof(List<>);
Type constructedListType;
type = item.Attributes["Type"].Value;
field = item.Attributes["Field"].Value;
if ((type == "Int32") || (type == "Int64") || (type == "Int16") || (type == "UInt32") || (type == "UInt64") || (type == "UInt16") || (type == "String") || (type == "Datetime") || (type == "Double") || (type == "Single"))
{
constructedListType = listType.MakeGenericType(Type.GetType(String.Format("{0}.{1}", "System", type)));
}
else
{
constructedListType = listType.MakeGenericType(Type.GetType(String.Format("{0}.{1}", WorkingNamespace, type)));
}
IList instance = (IList)Activator.CreateInstance(constructedListType);
但是我在 Java 生成泛型数组列表时遇到了一个问题,该数组列表的对象类型来自 xml。
**已编辑
type = attrMap.getNamedItem("Type").getNodeValue();
field = attrMap.getNamedItem("Field").getNodeValue();
type = reverseTypeConvert(type);
Object oList;
if ((type.equals("Integer") || type.equals("Long") || type.equals("Float") || type.equals("Short") || type.equals("String") || type.equals("Double") || type.equals("Date"))) {
oList = Class.forName(String.format("java.util.ArrayList<%s.%s>","java.util",type)).newInstance();
}
else {
oList = Class.forName(String.format("java.util.ArrayList<%s.%s>",this.workingPackage,type)).getGenericSuperclass();
}
if (!field.equals("none")) {
Method setMethod = cObj.getClass().getMethod(String.format("%s%s", "set",field), oList.getClass());
setMethod.invoke(cObj, oList);
}
deSerializeObject(node.getChildNodes(),oList);
所以,我在 Java 中找不到对应的 c# 代码。 感谢您的帮助!
好的,我们处理这个问题,我理解我的错误。 非常感谢。
【问题讨论】:
-
能贴出你试过的java代码吗?
-
为什么需要在运行时这样做?运行时的泛型真的不重要
-
我编辑了@Hirak 的问题。
-
请阅读 Java 中的 type erasure。
-
因为我需要转换列表的每个元素而不是只转换数组列表。此外,我正在编写通信协议,因此,序列化和反序列化需要在运行时进行。你有什么建议吗? @maress
标签: c# java generics reflection arraylist