Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.general.ArrayConverter.java

protected Object convertToArray(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass, final boolean toScript) {
    final Object result;
    final Class<?> valueClass = value.getClass();
    if (valueClass.isArray()) {
        final Object arr = Array.newInstance(expectedClass.getComponentType(), Array.getLength(value));

        for (int idx = 0; idx < Array.getLength(value); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(Array.get(value, idx),
                            expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(Array.get(value, idx),
                            expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }//from   w  ww.ja v a 2  s. c  o m
        result = arr;
    } else {
        final Collection<?> coll;
        if (value instanceof Collection<?>) {
            coll = (Collection<?>) value;
        } else {
            final List<Object> list = new ArrayList<Object>();
            final Iterator<?> it = (Iterator<?>) value;
            while (it.hasNext()) {
                list.add(it.next());
            }
            coll = list;
        }

        final Object arr = Array.newInstance(expectedClass.getComponentType(), coll.size());
        final Iterator<?> it = coll.iterator();
        for (int idx = 0; it.hasNext(); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(it.next(), expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(it.next(), expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }
        result = arr;
    }
    return result;
}

From source file:org.jabsorb.ng.serializer.impl.ArraySerializer.java

@Override
public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONArray jso = (JSONArray) o;
    final Class<?> cc = clazz.getComponentType();
    int i = 0;//from   ww w .j av  a 2 s .c  o  m

    try {
        // TODO: Is there a nicer way of doing this without all the ifs?
        if (clazz == int[].class) {
            final int arr[] = new int[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).intValue();
            }
            return arr;
        } else if (clazz == byte[].class) {
            final byte arr[] = new byte[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).byteValue();
            }
            return arr;
        } else if (clazz == short[].class) {
            final short arr[] = new short[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).shortValue();
            }
            return arr;
        } else if (clazz == long[].class) {
            final long arr[] = new long[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).longValue();
            }
            return arr;
        } else if (clazz == float[].class) {
            final float arr[] = new float[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).floatValue();
            }
            return arr;
        } else if (clazz == double[].class) {
            final double arr[] = new double[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).doubleValue();
            }
            return arr;
        } else if (clazz == char[].class) {
            final char arr[] = new char[jso.length()];
            for (; i < jso.length(); i++) {
                arr[i] = ((String) ser.unmarshall(state, cc, jso.get(i))).charAt(0);
            }
            return arr;
        } else if (clazz == boolean[].class) {
            final boolean arr[] = new boolean[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Boolean) ser.unmarshall(state, cc, jso.get(i))).booleanValue();
            }
            return arr;
        } else {
            final Object arr[] = (Object[]) Array.newInstance(cc != null ? cc : java.lang.Object.class,
                    jso.length());
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ser.unmarshall(state, cc, jso.get(i));
            }

            if (List.class.isAssignableFrom(clazz)) {
                // List requested
                return Arrays.asList(arr);
            }

            // Array requested
            return arr;
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage() + " not found in json object", e);
    }
}

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

/**
 * Method to populate a collection type which can be an array or a {@link Collection}.
 *
 * @param field The field in which the generated value will be set
 * @return an random collection matching type of field.
 * @throws IllegalAccessException    Thrown when the generated value cannot be set to the given field
 * @throws NoSuchMethodException     Thrown when there is no setter for the given field
 * @throws InvocationTargetException Thrown when the setter of the given field can not be invoked
 *//* w  w w. ja  v  a2 s .c om*/
private Object getRandomCollection(final Field field)
        throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    Class<?> fieldType = field.getType();

    //Array type
    if (fieldType.isArray()) {
        return Array.newInstance(fieldType.getComponentType(), 0);
    }

    //Collection type
    Object collection = null;
    if (List.class.isAssignableFrom(fieldType)) {
        collection = Collections.emptyList();
    } else if (NavigableSet.class.isAssignableFrom(fieldType)) {
        collection = new TreeSet();
    } else if (SortedSet.class.isAssignableFrom(fieldType)) {
        collection = new TreeSet();
    } else if (Set.class.isAssignableFrom(fieldType)) {
        collection = Collections.emptySet();
    } else if (Deque.class.isAssignableFrom(fieldType)) {
        collection = new ArrayDeque();
    } else if (Queue.class.isAssignableFrom(fieldType)) {
        collection = new ArrayDeque();
    } else if (NavigableMap.class.isAssignableFrom(fieldType)) {
        collection = new TreeMap();
    } else if (SortedMap.class.isAssignableFrom(fieldType)) {
        collection = new TreeMap();
    } else if (Map.class.isAssignableFrom(fieldType)) {
        collection = Collections.emptyMap();
    } else if (Collection.class.isAssignableFrom(fieldType)) {
        collection = Collections.emptyList();
    }

    return collection;
}

From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java

protected Object provideArrayValue(Member member, TypeLiteral<?> type, Class<?> memberType,
        Predicate<Binding> filter) {
    Class<?> componentType = memberType.getComponentType();
    Set<Binding<?>> set = getSortedBindings(componentType, filter);
    // TODO should we return an empty array when no matches?
    // FWIW Spring seems to return null
    if (set.isEmpty()) {
        return null;
    }/* w ww .  ja  va  2  s  .co  m*/
    Object array = Array.newInstance(componentType, set.size());
    int index = 0;
    for (Binding<?> binding : set) {
        Object value = binding.getProvider().get();
        Array.set(array, index++, value);
    }
    return array;
}

From source file:org.apache.sling.models.impl.injectors.ValueMapInjector.java

public Object getValue(@Nonnull Object adaptable, String name, @Nonnull Type type,
        @Nonnull AnnotatedElement element, @Nonnull DisposalCallbackRegistry callbackRegistry) {
    ValueMap map = getValueMap(adaptable);
    if (map == null) {
        return null;
    } else if (type instanceof Class<?>) {
        Class<?> clazz = (Class<?>) type;
        try {//from   w w  w  . jav  a 2 s  .  c o m
            return map.get(name, clazz);
        } catch (ClassCastException e) {
            // handle case of primitive/wrapper arrays
            if (clazz.isArray()) {
                Class<?> componentType = clazz.getComponentType();
                if (componentType.isPrimitive()) {
                    Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType);
                    if (wrapper != componentType) {
                        Object wrapperArray = map.get(name, Array.newInstance(wrapper, 0).getClass());
                        if (wrapperArray != null) {
                            return unwrapArray(wrapperArray, componentType);
                        }
                    }
                } else {
                    Class<?> primitiveType = ClassUtils.wrapperToPrimitive(componentType);
                    if (primitiveType != componentType) {
                        Object primitiveArray = map.get(name, Array.newInstance(primitiveType, 0).getClass());
                        if (primitiveArray != null) {
                            return wrapArray(primitiveArray, componentType);
                        }
                    }
                }
            }
            return null;
        }
    } else if (type instanceof ParameterizedType) {
        // list support
        ParameterizedType pType = (ParameterizedType) type;
        if (pType.getActualTypeArguments().length != 1) {
            return null;
        }
        Class<?> collectionType = (Class<?>) pType.getRawType();
        if (!(collectionType.equals(Collection.class) || collectionType.equals(List.class))) {
            return null;
        }

        Class<?> itemType = (Class<?>) pType.getActualTypeArguments()[0];
        Object array = map.get(name, Array.newInstance(itemType, 0).getClass());
        if (array == null) {
            return null;

        }

        return Arrays.asList((Object[]) array);
    } else {
        log.debug("ValueMapInjector doesn't support non-class types {}", type);
        return null;
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

/**
 * Return ComponentType, might need to look at the GenericType
 * @param pd ParameterDesc or null if return
 * @param operationDesc OperationDescription
 * @param msrd MarshalServiceRuntimeDescription
 * @return// w w w .ja v a2 s.  c  o  m
 */
private static Class getComponentType(ParameterDescription pd, OperationDescription operationDesc,
        MarshalServiceRuntimeDescription msrd) {
    Class componentType = null;
    if (log.isDebugEnabled()) {
        log.debug("start getComponentType");
        log.debug(" ParameterDescription=" + pd);
    }

    // Determine if array, list, or other
    Class cls = null;
    if (pd == null) {
        cls = operationDesc.getResultActualType();
    } else {
        cls = pd.getParameterActualType();
    }

    if (cls != null) {
        if (cls.isArray()) {
            componentType = cls.getComponentType();
        } else if (List.class.isAssignableFrom(cls)) {
            if (log.isDebugEnabled()) {
                log.debug("Parameter is a List: " + cls);
            }
            Method method = msrd.getMethod(operationDesc);
            if (log.isDebugEnabled()) {
                log.debug("Method is: " + method);
            }
            Type genericType = null;
            if (pd == null) {
                genericType = method.getGenericReturnType();
            } else {
                ParameterDescription[] pds = operationDesc.getParameterDescriptions();
                for (int i = 0; i < pds.length; i++) {
                    if (pds[i] == pd) {
                        genericType = method.getGenericParameterTypes()[i];
                    }
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("genericType is: " + genericType.getClass() + " " + genericType);
            }
            if (genericType instanceof Class) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof Class");
                }
                componentType = String.class;
            } else if (genericType instanceof ParameterizedType) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof ParameterizedType");
                }
                ParameterizedType pt = (ParameterizedType) genericType;
                if (pt.getRawType() == Holder.class) {
                    if (log.isDebugEnabled()) {
                        log.debug(" strip off holder");
                    }
                    genericType = pt.getActualTypeArguments()[0];
                    if (genericType instanceof Class) {
                        componentType = String.class;
                    } else if (genericType instanceof ParameterizedType) {
                        pt = (ParameterizedType) genericType;
                    }
                }
                if (componentType == null) {
                    Type comp = pt.getActualTypeArguments()[0];
                    if (log.isDebugEnabled()) {
                        log.debug(" comp =" + comp.getClass() + " " + comp);
                    }
                    if (comp instanceof Class) {
                        componentType = (Class) comp;
                    } else if (comp instanceof ParameterizedType) {
                        componentType = (Class) ((ParameterizedType) comp).getRawType();
                    }
                }
            }

        }
    }

    if (log.isDebugEnabled()) {
        log.debug("end getComponentType=" + componentType);
    }
    return componentType;
}

From source file:io.konik.utils.RandomInvoiceGenerator.java

private Object createNewInstance(Class<?> root) throws InstantiationException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    try {/*  w  ww  .j  a  v a  2s  .  co m*/
        if (root.isArray()) {
            Object[] array = (Object[]) Array.newInstance(root.getComponentType(), 1);
            Class<?> componentType = root.getComponentType();
            array[0] = populteData(componentType, componentType.getName());
            return array;
        }
        return root.newInstance();
    } catch (IllegalAccessException e) {
        Constructor<?> biggestConstructor = findBiggestConstructor(root);
        //for each parameter populate data
        Class<?>[] constructorParameters = biggestConstructor.getParameterTypes();
        Object[] constructorParameterObjects = new Object[constructorParameters.length];
        for (int i = 0; i < constructorParameters.length; i++) {
            Class<?> cp = constructorParameters[i];
            constructorParameterObjects[i] = populteData(cp, biggestConstructor.getName());
        }
        return biggestConstructor.newInstance(constructorParameterObjects);
    } catch (InstantiationException e) {
        if (root.equals(CommonTax.class)) {
            //            return ZfDateFactory.create(supportedDateFormatts[random.nextInt(3)]);
        }
        //         throw e;
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.struts.util.RequestUtils.java

/**
 * <p>If the given form bean can accept multiple FormFile objects but the user only uploaded a single, then
 * the property will not match the form bean type.  This method performs some simple checks to try to accommodate
 * that situation.</p>/*  www . ja  va  2s.c o m*/
 *
 * @param bean
 * @param name
 * @param parameterValue
 * @return
 * @throws ServletException if the introspection has any errors.
 */
private static Object rationalizeMultipleFileProperty(Object bean, String name, Object parameterValue)
        throws ServletException {
    if (!(parameterValue instanceof FormFile)) {
        return parameterValue;
    }

    FormFile formFileValue = (FormFile) parameterValue;
    try {
        Class propertyType = PropertyUtils.getPropertyType(bean, name);

        if (propertyType == null) {
            return parameterValue;
        }

        if (List.class.isAssignableFrom(propertyType)) {
            ArrayList list = new ArrayList(1);
            list.add(formFileValue);
            return list;
        }

        if (propertyType.isArray() && propertyType.getComponentType().equals(FormFile.class)) {
            return new FormFile[] { formFileValue };
        }

    } catch (IllegalAccessException e) {
        throw new ServletException(e);
    } catch (InvocationTargetException e) {
        throw new ServletException(e);
    } catch (NoSuchMethodException e) {
        throw new ServletException(e);
    }

    // no changes
    return parameterValue;

}

From source file:net.sf.morph.util.TestUtils.java

/**
 * Return a "not-same" instance.// ww  w  .  ja  v a2 s . c  o  m
 * @param type
 * @param o
 * @return
 */
public static Object getDifferentInstance(Class type, Object o) {
    if (type == null) {
        throw new IllegalArgumentException("Non-null type must be specified");
    }
    if (type.isPrimitive()) {
        type = ClassUtils.getPrimitiveWrapper(type);
    }
    if (o != null && !type.isInstance(o)) {
        throw new IllegalArgumentException("Negative example object should be of type " + type);
    }
    if (type == Number.class) {
        type = Integer.class;
    }
    if (Number.class.isAssignableFrom(type)) {
        byte b = (byte) (o == null ? 0 : ((Number) o).byteValue() + 1);
        try {
            return type.getConstructor(ONE_STRING).newInstance(new Object[] { Byte.toString(b) });
        } catch (Exception e) {
            throw e instanceof RuntimeException ? (RuntimeException) e : new NestableRuntimeException(e);
        }
    }
    if (type == Character.class) {
        char c = (char) (o == null ? 0 : ((Character) o).charValue() + 1);
        return new Character(c);
    }
    if (type == Boolean.class) {
        return o != null && ((Boolean) o).booleanValue() ? Boolean.FALSE : Boolean.TRUE;
    }
    if (type.isArray()) {
        return Array.newInstance(type.getComponentType(), 0);
    }
    if (type == Class.class) {
        return o == Object.class ? Class.class : Object.class;
    }
    return ClassUtils.newInstance(convertCommonInterfaces(type));
}