【问题标题】:Converting array of Objects to array of custom Types将对象数组转换为自定义类型数组
【发布时间】:2011-06-23 11:33:46
【问题描述】:

我有一种方法可以为所需类型构建数组。它适用于原始类型。但是当我有自定义对象数组时它不起作用。所以我已经对其进行了调整。但它仍然失败。 代码是这样的:

    private Object buildArray(  String type,   Object object) {
    final Class<?> requiredType =  loadClass(type);
    final String typeName = type.substring(2).replace(";", "").trim();
        Object[] array = ((Object[]) object);
        ArrayList<Object> arrayList = new ArrayList<Object>(array.length);
        for (Object customObj : array) {
            arrayList.add(castToRequiredType(typeName, customObj));
        }
        return arrayList.toArray();
 }

在这个castToRequiredType 中:将CustomObject 转换为CustomType,其中CustomType 是一个类。并且要构建的数组的类型是CustomType。我被困在动态构建CustomType 的数组中。

欢迎在这方面提供任何帮助。 提前致谢。

【问题讨论】:

  • 这段代码的意图真的很难理解。您对此的总体目标是什么?
  • 总体目标是调用采用 customObject[] 类型参数的 API。我必须使用 castToRequiredType 构建每个 CustomObject。此 CustomObject 可以是 MyCustoType、YourCustomType 等。

标签: java arrays list reflection toarray


【解决方案1】:

如果您有一个Object 数组,您可以使用Arrays.copyOf 将其转换为不同的类型:

CustomType[] ca = Arrays
  .copyOf(array, array.length, CustomType[].class);

【讨论】:

  • 好吧,我尝试像这样替换最后一个 return Arrays.copyOf(arrayList.toArray(), arrayList.size(), customType.newInstance());但它不编译 Arrays 类型中的方法 copyOf(U[], int, Class extends T[]>) 不适用于参数(Object[], int, capture#40-of ?)谢谢寻求帮助:)
  • @java_enthu:我的回答有误,但我已修复。此行替换您的for-loop。您不需要先构造ArrayList。这直接适用于您的array
  • @space_cowboy :我将循环替换为 Class> customType = loadClass(typeName); Arrays.copyOf(array, array.length,customType);我仍然得到相同的编译错误。 Arrays 类型中的方法 copyOf(U[], int, Class extends T[]>) 不适用于参数 (Object[], int, Class)
  • @java_enthu: 抱歉,如果在编译时不知道类,这种方法似乎确实行不通。
  • 无论如何感谢您的快速帮助 :) 任何其他方法或解决方法您认为哪个可行?
【解决方案2】:

谢谢我已经用Axis's Array Util For the same解决了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-31
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多