简体   繁体   English

java 如何将未知的 object 转换为数组

[英]java how to cast unknown object to an array

I have following code:我有以下代码:

Object result = joinPoint.proceed();

if(result instanceof Publisher) {
  return (Publisher<?>)result;
}

if(result instanceof Iterable<?>) {
  return Flux.fromIterable((Iterable<?>)result);
}

if(result.getClass().isArray()) {
  //ERROR HERE: no instance(s) of type variable(s) T exist so that Object conforms to T[]
  return Flux.fromArray(result);
}

I want to pass the result as an array to Flux.fromArray but I don't know how to cast it to an array?我想将result作为数组传递给Flux.fromArray但我不知道如何将其转换为数组? Or any better solution?或者有什么更好的解决方案? I want to return a Publisher我想退回 Publisher

Flux does not work with primitive types, so if you want to use, for example Flux.fromArray() , then you should convert your array of primitives to array of objects. Flux 不适用于基元类型,因此如果您想使用,例如Flux.fromArray() ,那么您应该将基元数组转换为对象数组。

To simplify converting there is ArrayUtils.toObject() method from org.apache.commons.lang3.ArrayUtils , but it has multiple implementations depending on the primitive type: long , byte , int and etc.为了简化转换,有来自org.apache.commons.lang3.ArrayUtilsArrayUtils.toObject()方法,但它有多种实现,具体取决于原始类型: longbyteint等。

However, in your case you have to somehow determine the actual type of values within the array.但是,在您的情况下,您必须以某种方式确定数组中值的实际类型。 It is possible, but not really good solution, it is because you honestly have not a good design.这是可能的,但不是很好的解决方案,这是因为你真的没有一个好的设计。

The method to achieve this would look like this:实现此目的的方法如下所示:

public Object[] convert(Object array) {
    Class<?> componentType = array.getClass().getComponentType();
    if (componentType.isPrimitive()) {
        if (array instanceof boolean[]) {
            return ArrayUtils.toObject((boolean[]) array);

        } else if (array instanceof int[]) {
            return ArrayUtils.toObject((int[]) array);

        } else if (array instanceof long[]) {
            return ArrayUtils.toObject((long[]) array);

        } else if (array instanceof short[]) {
            return ArrayUtils.toObject((short[]) array);

        } else if (array instanceof double[]) {
            return ArrayUtils.toObject((double[]) array);

        } else if (array instanceof char[]) {
            return ArrayUtils.toObject((char[]) array);

        } else if (array instanceof byte[]) {
            return ArrayUtils.toObject((byte[]) array);

        } else if (array instanceof float[]) {
            return ArrayUtils.toObject((float[]) array);
        }
    }
    return (Object[]) array;
}

And your piece of code:还有你的一段代码:

if(result.getClass().isArray()) {
    return Flux.fromArray(convert(result));
}

It would work the way you expected, however, as I said it looks like a bad design.它会按您预期的方式工作,但是,正如我所说,它看起来像是一个糟糕的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM