Home > Software design >  java how to cast unknown object to an array
java how to cast unknown object to an array

Time:02-01

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? Or any better solution? I want to return a Publisher

CodePudding user response:

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.

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.

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.

  • Related