Java将未知的原始数组转换为对象数组 [英] Java Convert Unknown Primitive Array to Object Array
问题描述
我一直在尝试创建自己的库,以使用反射来检查方法命名模式和方法返回类型,以从类到xml以及从xml到类实例的原始类型进行序列化和反序列化.
I have been trying to create my own library to serialize and de-serialize primitive types from a class to xml and from xml to a class instance using reflection to examine method naming patterns and method return types.
到目前为止,我已经能够使用所有基本的基本类型进行此操作,但是我被困在序列化相同基本类型的数组上.
So far I have been able to do this with all the basic primitive types but I got stuck on serializing an array of the same primitives.
例如,我调用class方法以获取基元数组:
For example I invoke the class method to get the array of primitives:
method.invoke(clazz, (Object[])null);
此方法将仅返回原始数组int[], double[], float[], char[]
等,尽管我们不知道它将是哪一个.
This method will return only a primitive array int[], double[], float[], char[]
etc. though we don't know which one it will be.
我尝试使用泛型,例如
T t = (T)method.invoke(clazz, (Object[])null);
T[] t = (T[])method.invoke(clazz, (Object[])null);
但是它不允许我从原始数组转换为对象.
But it doesn't let me cast from the primitive array to an object.
假设我们不知道类型,就不能使用Array.newInstance
.
And you can't use Array.newInstance
assuming we don't know the type.
有没有一种方法可以将这种原始数组转换为通用的Object数组.
Is there a way that I can convert this array of primitives to say an Object array in a generic manner.
以通用方式表示,无需知道或检查数组的类型是什么.还是我应该循环浏览所有原始类型并分别处理所有这些原始类型.
In a generic manner meaning without needing to know or checking what the type of the array is. Or should I just cycle through all the primitive types and handle all of them separately.
我可以同时做这两种方式,我想以通用方式执行此操作的唯一原因是减少冗余代码.
I can do this both ways the only reason I want to do this in a generic manner is to cut down on the redundant code.
谢谢.
推荐答案
您可以使用 查看全文