Example usage for java.lang.reflect Array set

List of usage examples for java.lang.reflect Array set

Introduction

In this page you can find the example usage for java.lang.reflect Array set.

Prototype

public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Sets the value of the indexed component of the specified array object to the specified new value.

Usage

From source file:org.datanucleus.store.scalaris.fieldmanager.FetchFieldManager.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object fetchObjectFieldInternal_RelationTypeNone(AbstractMemberMetaData mmd, String memberName,
        ClassLoaderResolver clr) throws JSONException {
    final Object returnValue;
    if (mmd.getTypeConverterName() != null) {
        // User-defined converter
        TypeConverter<Object, Object> conv = ec.getNucleusContext().getTypeManager()
                .getTypeConverterForName(mmd.getTypeConverterName());
        Class<?> datastoreType = TypeConverterHelper.getDatastoreTypeForTypeConverter(conv, mmd.getType());
        if (datastoreType == String.class) {
            returnValue = (Object) conv.toMemberType(result.getString(memberName));
        } else if (datastoreType == Boolean.class) {
            returnValue = conv.toMemberType(result.getBoolean(memberName));
        } else if (datastoreType == Double.class) {
            returnValue = conv.toMemberType(result.getDouble(memberName));
        } else if (datastoreType == Float.class) {
            returnValue = conv.toMemberType(result.getDouble(memberName));
        } else if (datastoreType == Integer.class) {
            returnValue = conv.toMemberType(result.getInt(memberName));
        } else if (datastoreType == Long.class) {
            returnValue = conv.toMemberType(result.getLong(memberName));
        } else {//from   ww w . j a va  2  s . co m
            returnValue = null;
        }
        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), returnValue, true);
        }
    } else if (Boolean.class.isAssignableFrom(mmd.getType())) {
        return result.getBoolean(memberName);
    } else if (Integer.class.isAssignableFrom(mmd.getType())) {
        return result.getInt(memberName);
    } else if (Long.class.isAssignableFrom(mmd.getType())) {
        return result.getLong(memberName);
    } else if (Double.class.isAssignableFrom(mmd.getType())) {
        return result.getDouble(memberName);
    } else if (Date.class.isAssignableFrom(mmd.getType())) {
        Long dateValue = result.getLong(memberName);
        return new Date(dateValue);
    } else if (Enum.class.isAssignableFrom(mmd.getType())) {
        if (mmd.getType().getEnumConstants() != null) {
            return mmd.getType().getEnumConstants()[result.getInt(memberName)];
        } else {
            return Enum.valueOf(mmd.getType(), (String) result.get(memberName));
        }
    } else if (BigDecimal.class.isAssignableFrom(mmd.getType())
            || BigInteger.class.isAssignableFrom(mmd.getType())) {
        return TypeConversionHelper.convertTo(result.get(memberName), mmd.getType());
    } else if (Collection.class.isAssignableFrom(mmd.getType())) {
        // Collection<Non-PC>
        Collection<Object> coll;
        try {
            Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(),
                    mmd.getOrderMetaData() != null);
            coll = (Collection<Object>) instanceType.newInstance();
        } catch (Exception e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        }

        JSONArray array = result.getJSONArray(memberName);
        Class<?> elementCls = null;
        if (mmd.getCollection() != null && mmd.getCollection().getElementType() != null) {
            elementCls = clr.classForName(mmd.getCollection().getElementType());
        }
        for (int i = 0; i < array.length(); i++) {
            if (array.isNull(i)) {
                coll.add(null);
            } else {
                Object value = array.get(i);
                if (elementCls != null) {
                    coll.add(TypeConversionHelper.convertTo(value, elementCls));
                } else {
                    coll.add(value);
                }
            }
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), coll, true);
        }
        return coll;
    } else if (Map.class.isAssignableFrom(mmd.getType())) {
        // Map<Non-PC, Non-PC>
        Map map;
        try {
            Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false);
            map = (Map) instanceType.newInstance();
        } catch (Exception e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        }

        JSONObject mapValue = result.getJSONObject(memberName);
        Iterator<?> keyIter = mapValue.keys();
        Class<?> keyCls = null;
        if (mmd.getMap() != null && mmd.getMap().getKeyType() != null) {
            keyCls = clr.classForName(mmd.getMap().getKeyType());
        }
        Class<?> valCls = null;
        if (mmd.getMap() != null && mmd.getMap().getValueType() != null) {
            valCls = clr.classForName(mmd.getMap().getValueType());
        }

        while (keyIter.hasNext()) {
            Object jsonKey = keyIter.next();

            Object key = jsonKey;
            if (keyCls != null) {
                key = TypeConversionHelper.convertTo(jsonKey, keyCls);
            }

            Object jsonVal = mapValue.get((String) key);
            Object val = jsonVal;
            if (valCls != null) {
                val = TypeConversionHelper.convertTo(jsonVal, valCls);
            }
            map.put(key, val);
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), map, true);
        }
        return map;
    } else if (mmd.getType().isArray()) {
        // Non-PC[]
        JSONArray arrayJson = result.getJSONArray(memberName);
        Object array = Array.newInstance(mmd.getType().getComponentType(), arrayJson.length());
        for (int i = 0; i < arrayJson.length(); i++) {
            if (arrayJson.isNull(i)) {
                Array.set(array, i, null);
            } else {
                Object value = arrayJson.get(i);
                Array.set(array, i, TypeConversionHelper.convertTo(value, mmd.getType().getComponentType()));
            }
        }
        return array;
    } else {
        // Fallback to built-in type converters
        boolean useLong = false;
        ColumnMetaData[] colmds = mmd.getColumnMetaData();
        if (colmds != null && colmds.length == 1) {
            JdbcType jdbcType = colmds[0].getJdbcType();
            if (jdbcType != null) {
                String jdbc = jdbcType.name();
                if (jdbc != null && (jdbc.equalsIgnoreCase("INTEGER") || jdbc.equalsIgnoreCase("NUMERIC"))) {
                    useLong = true;
                }
            }
        }
        TypeConverter strConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(mmd.getType(),
                String.class);
        TypeConverter longConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(mmd.getType(),
                Long.class);

        if (useLong && longConv != null) {
            returnValue = longConv.toMemberType(result.getLong(memberName));
        } else if (!useLong && strConv != null) {
            returnValue = strConv.toMemberType((String) result.get(memberName));
        } else if (!useLong && longConv != null) {
            returnValue = longConv.toMemberType(result.getLong(memberName));
        } else {
            returnValue = TypeConversionHelper.convertTo(result.get(memberName), mmd.getType());
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), returnValue, true);
        }
    }
    return returnValue;
}

From source file:com.google.flatbuffers.Table.java

@SuppressWarnings("unchecked")
@Override/* www.  j a v  a2 s . c  o  m*/
public int clone(FlatBufferBuilder builder, Map<String, Object> mutate) throws Exception {
    int root_table = -1;
    Class<?> cls = this.getClass();
    HashMap<String, Object> v = new HashMap<String, Object>();
    try {
        //b0. phan loai method
        List<Method> msAdd = new ArrayList<Method>();
        List<Method> msGet = new ArrayList<Method>();
        HashMap<String, Method> msCreateVector = new HashMap<String, Method>();
        Method[] ms = this.getClass().getDeclaredMethods();
        for (Method m : ms) {
            String sMethodName = m.getName();
            if (m.getParameterTypes().length == 0 && !sMethodName.endsWith("AsByteBuffer"))
                msGet.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("add"))
                msAdd.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("create")
                    && sMethodName.endsWith("Vector"))
                msCreateVector.put(sMethodName, m);
        }
        //b1. lay ds thuoc tinh va gia tri
        for (Method m : msGet) {
            String sMethodName = m.getName();
            if (sMethodName.endsWith("Length")) {
                int ii = sMethodName.lastIndexOf("Length");
                String sMethodName1 = sMethodName.substring(0, ii);
                int iLength = 0;
                try {
                    iLength = (int) m.invoke(this, new Object[] {});
                } catch (Exception e) {
                }
                List<Object> l = new ArrayList<>();
                for (int i = 0; i < iLength; i++) {
                    Method m1 = this.getClass().getDeclaredMethod(sMethodName1,
                            new Class<?>[] { Integer.TYPE });
                    Object oKq = m1.invoke(this, new Object[] { i });
                    l.add(oKq);
                }
                v.put(sMethodName1, l);
            } else {
                Object oKq = m.invoke(this, new Object[] {});
                v.put(sMethodName, oKq);
            }
        }
        //b2. khoi tao gia tri cho builder
        for (Entry<String, Object> e : v.entrySet()) {
            String sKey = e.getKey();
            Object oValue = e.getValue();
            Object oNewValue = mutate != null ? mutate.get(sKey) : null;
            if (oValue instanceof String || oNewValue instanceof String) {
                int keyOffset = builder
                        .createString(oNewValue == null ? oValue.toString() : oNewValue.toString());
                v.put(sKey, keyOffset);
            } else if (oValue instanceof List || oNewValue instanceof List) {
                List<?> oV = (List<?>) (oNewValue == null ? oValue : oNewValue);
                int iLen = ((List<?>) oV).size();
                if (iLen <= 0)
                    v.put(sKey, null);
                else {
                    Object obj = ((List<?>) oV).get(0);
                    if (obj instanceof Table || obj instanceof Struct) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<?>) oV).get(i);
                            int offset = ((IFlatBuffer) obj).clone(builder, null);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else if (obj instanceof String) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<String>) oV).get(i);
                            int offset = builder.createString((CharSequence) obj);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else {
                        int keyOffset = -1;
                        Method m = msCreateVector.get("create" + WordUtils.capitalize(sKey) + "Vector");
                        Class<?> subCls = Class.forName(m.getParameterTypes()[1].getName());
                        Class<?> objType = subCls.getComponentType();
                        String objTypeName = objType.getSimpleName();
                        Method mo = Number.class.getDeclaredMethod(objTypeName + "Value", new Class<?>[] {});
                        Object aObject = Array.newInstance(objType, iLen);
                        for (int i = 0; i < iLen; i++)
                            Array.set(aObject, i, mo.invoke(((List<Number>) oV).get(i), new Object[] {}));
                        keyOffset = (int) m.invoke(null, new Object[] { builder, aObject });
                        if (keyOffset != -1)
                            v.put(sKey, keyOffset);
                    }
                }
            } else if (oValue instanceof Table || oValue instanceof Struct || oNewValue instanceof Table
                    || oNewValue instanceof Struct) {
                int keyOffset = -1;
                if (oNewValue != null)
                    keyOffset = ((IFlatBuffer) oNewValue).clone(builder, mutate);
                else
                    keyOffset = ((IFlatBuffer) oValue).clone(builder, mutate);
                if (keyOffset != -1)
                    v.put(sKey, keyOffset);
            } else {
                if (oNewValue != null)
                    v.put(sKey, oNewValue);
            }
        }
        //b3. gan gia tri cho clone object
        Method m = cls.getDeclaredMethod("start" + cls.getSimpleName(),
                new Class<?>[] { FlatBufferBuilder.class });
        m.invoke(null, new Object[] { builder });
        for (Method mAdd : msAdd) {
            String sFieldName = mAdd.getName().replace("add", "");
            sFieldName = WordUtils.uncapitalize(sFieldName);
            Object oFieldValue = v.get(sFieldName);
            if (oFieldValue != null && !(oFieldValue instanceof Table || oFieldValue instanceof Struct)) {
                mAdd.invoke(null, new Object[] { builder, oFieldValue });
            }
        }
        m = cls.getDeclaredMethod("end" + cls.getSimpleName(), new Class<?>[] { FlatBufferBuilder.class });
        root_table = (int) m.invoke(null, new Object[] { builder });
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return root_table;
}

From source file:com.xwtec.xwserver.util.json.JSONArray.java

/**
 * Creates a java array from a JSONArray.<br>
 *//*from   w  w w  .j a va2 s.c  om*/
public static Object toArray(JSONArray jsonArray, Object root, JsonConfig jsonConfig) {
    Class objectClass = root.getClass();
    if (jsonArray.size() == 0) {
        return Array.newInstance(objectClass, 0);
    }

    int[] dimensions = JSONArray.getDimensions(jsonArray);
    Object array = Array.newInstance(objectClass == null ? Object.class : objectClass, dimensions);
    int size = jsonArray.size();
    for (int i = 0; i < size; i++) {
        Object value = jsonArray.get(i);
        if (JSONUtils.isNull(value)) {
            Array.set(array, i, null);
        } else {
            Class type = value.getClass();
            if (JSONArray.class.isAssignableFrom(type)) {
                Array.set(array, i, toArray((JSONArray) value, root, jsonConfig));
            } else if (String.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type)
                    || JSONUtils.isNumber(type) || Character.class.isAssignableFrom(type)
                    || JSONFunction.class.isAssignableFrom(type)) {
                if (objectClass != null && !objectClass.isAssignableFrom(type)) {
                    value = JSONUtils.getMorpherRegistry().morph(objectClass, value);
                }
                Array.set(array, i, value);
            } else {
                try {
                    Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(root.getClass(), null);
                    Array.set(array, i, JSONObject.toBean((JSONObject) value, newRoot, jsonConfig));
                } catch (JSONException jsone) {
                    throw jsone;
                } catch (Exception e) {
                    throw new JSONException(e);
                }
            }
        }
    }
    return array;
}

From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java

private Object initializeIndexedProperty(Object parentObject, String property,
        PropertyDescriptor propertyMetaData, List<ArrayMetaData> objectMetaData, String propertyPath)
        throws Exception {
    Object element = null;//from ww w. j  a va 2s .c  o  m

    //ArrayUri
    String arrayUri = null;
    Integer arrayIndex = 0;
    if (propertyPath.endsWith("]")) {
        int lastIndex = propertyPath.lastIndexOf('[');
        arrayUri = propertyPath.substring(0, lastIndex);
        arrayIndex = Integer.parseInt(propertyPath.substring(lastIndex + 1, propertyPath.length() - 1).trim());
    }
    ArrayMetaData arrayMetaData = null;
    for (ArrayMetaData local : objectMetaData) {
        if (local.arrayUri.equals(arrayUri)) {
            arrayMetaData = local;
            break;
        }
    }

    //Find the Class of the elementType
    String elementTypeName = arrayMetaData.arrayClass;
    Class elementType = null;
    if (elementTypeName != null && elementTypeName.trim().length() > 0 && !elementTypeName.equals("null")) {
        elementType = Thread.currentThread().getContextClassLoader().loadClass(arrayMetaData.arrayClass);
    } else {
        //Figure out the element type from the Property Information
        //This happens when a brand new object is created on the device and is being synced
        //with the backend
        //The MobileObject Framework on the device does not know about any Class level information
        //of the remote bean
        //The Limitation of this is that:
        //
        //* Indexed Properties if Collections must be Parameterized with Concrete Types
        //* Indexed Properties if Arrays must be Arrays of Concrete Types
        if (!propertyMetaData.getPropertyType().isArray()) {
            ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod()
                    .getGenericReturnType();
            Type[] actualTypes = returnType.getActualTypeArguments();
            for (Type actualType : actualTypes) {
                elementType = (Class) actualType;
            }
        } else {
            elementType = propertyMetaData.getPropertyType().getComponentType();
        }
    }

    //An IndexedProperty
    Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    //Initialize the IndexedProperty (An Array or Collection)
    if (propertyMetaData.getPropertyType().isArray()) {
        int arraySize = arrayMetaData.arrayLength;
        if (indexedProperty == null) {
            //Initialize the Array with Size from Object Meta Data               
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                    Array.newInstance(elementType, arraySize));
        } else {
            //Make sure the Array Size matches
            int actualSize = Array.getLength(indexedProperty);
            if (actualSize != arraySize) {
                //Re-set the existing Array
                PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                        Array.newInstance(elementType, arraySize));
            }
        }
    } else {
        if (indexedProperty == null) {
            //Handle Collection Construction
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList());
        }
    }

    //Check to see if the index specified by the field requires creation of new
    //element
    indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    if (!propertyMetaData.getPropertyType().isArray()) {
        try {
            element = PropertyUtils.getIndexedProperty(parentObject, property);
        } catch (IndexOutOfBoundsException iae) {
            Object newlyInitialized = elementType.newInstance();
            ((Collection) indexedProperty).add(newlyInitialized);
            element = newlyInitialized;
        }
    } else {
        element = PropertyUtils.getIndexedProperty(parentObject, property);
        if (element == null) {
            Object newlyInitialized = elementType.newInstance();
            Array.set(indexedProperty, arrayIndex, newlyInitialized);
            element = newlyInitialized;
        }
    }

    return element;
}

From source file:com.flexive.faces.renderer.FxSelectRenderer.java

/**
 * Convert select many values to given array class
 *
 * @param context      faces context//from ww w. j a va2 s.  c  o  m
 * @param uiSelectMany select many component
 * @param arrayClass   the array class
 * @param newValues    new values to convert
 * @return converted values
 * @throws ConverterException on errors
 */
protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class arrayClass,
        String[] newValues) throws ConverterException {

    Object result;
    Converter converter;
    int len = (null != newValues ? newValues.length : 0);

    Class elementType = arrayClass.getComponentType();

    // Optimization: If the elementType is String, we don't need
    // conversion.  Just return newValues.
    if (elementType.equals(String.class))
        return newValues;

    try {
        result = Array.newInstance(elementType, len);
    } catch (Exception e) {
        throw new ConverterException(e);
    }

    // bail out now if we have no new values, returning our
    // oh-so-useful zero-length array.
    if (null == newValues)
        return result;

    // obtain a converter.

    // attached converter takes priority
    if (null == (converter = uiSelectMany.getConverter())) {
        // Otherwise, look for a by-type converter
        if (null == (converter = FxJsfComponentUtils.getConverterForClass(elementType, context))) {
            // if that fails, and the attached values are of Object type,
            // we don't need conversion.
            if (elementType.equals(Object.class))
                return newValues;
            StringBuffer valueStr = new StringBuffer();
            for (int i = 0; i < len; i++) {
                if (i == 0)
                    valueStr.append(newValues[i]);
                else
                    valueStr.append(' ').append(newValues[i]);
            }
            throw new ConverterException("Could not get a converter for " + String.valueOf(valueStr));
        }
    }

    if (elementType.isPrimitive()) {
        for (int i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])));
            }
        }
    } else {
        for (int i = 0; i < len; i++)
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
    }
    return result;
}

From source file:MultiMap.java

public static Object toArray(Object list, Class aClass) {
    if (list == null)
        return (Object[]) Array.newInstance(aClass, 0);

    if (list instanceof List) {
        List l = (List) list;
        if (aClass.isPrimitive()) {
            Object a = Array.newInstance(aClass, l.size());
            for (int i = 0; i < l.size(); i++)
                Array.set(a, i, l.get(i));
            return a;
        }/*w  w w.  j  a  v a2 s  . co m*/
        return l.toArray((Object[]) Array.newInstance(aClass, l.size()));

    }

    Object a = Array.newInstance(aClass, 1);
    Array.set(a, 0, list);
    return a;
}

From source file:org.enerj.apache.commons.beanutils.ConvertUtilsBean.java

/**
 * Convert an array of specified values to an array of objects of the
 * specified class (if possible).  If the specified Java class is itself
 * an array class, this class will be the type of the returned value.
 * Otherwise, an array will be constructed whose component type is the
 * specified class.//from  w ww.  jav  a  2s  . co  m
 *
 * @param values Values to be converted (may be null)
 * @param clazz Java array or element class to be converted to
 *
 * @exception ConversionException if thrown by an underlying Converter
 */
public Object convert(String values[], Class clazz) {

    Class type = clazz;
    if (clazz.isArray()) {
        type = clazz.getComponentType();
    }
    if (log.isDebugEnabled()) {
        log.debug("Convert String[" + values.length + "] to class '" + type.getName() + "[]'");
    }
    Converter converter = lookup(type);
    if (converter == null) {
        converter = lookup(String.class);
    }
    if (log.isTraceEnabled()) {
        log.trace("  Using converter " + converter);
    }
    Object array = Array.newInstance(type, values.length);
    for (int i = 0; i < values.length; i++) {
        Array.set(array, i, converter.convert(type, values[i]));
    }
    return (array);

}

From source file:org.crank.javax.faces.component.MenuRenderer.java

protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class<?> arrayClass,
        String[] newValues) throws ConverterException {

    Object result = null;//from  w  w w.ja va  2  s  . com
    Converter converter = null;
    int len = (null != newValues ? newValues.length : 0);

    Class<?> elementType = arrayClass.getComponentType();

    // Optimization: If the elementType is String, we don't need
    // conversion.  Just return newValues.
    if (elementType.equals(String.class)) {
        return newValues;
    }

    try {
        result = Array.newInstance(elementType, len);
    } catch (Exception e) {
        throw new ConverterException(e);
    }

    // bail out now if we have no new values, returning our
    // oh-so-useful zero-length array.
    if (null == newValues) {
        return result;
    }

    // obtain a converter.

    // attached converter takes priority
    if (null == (converter = uiSelectMany.getConverter())) {
        // Otherwise, look for a by-type converter
        if (null == (converter = Util.getConverterForClass(elementType, context))) {
            // if that fails, and the attached values are of Object type,
            // we don't need conversion.
            if (elementType.equals(Object.class)) {
                return newValues;
            }
            StringBuffer valueStr = new StringBuffer();
            for (int i = 0; i < len; i++) {
                if (i == 0) {
                    valueStr.append(newValues[i]);
                } else {
                    valueStr.append(' ').append(newValues[i]);
                }
            }
            Object[] params = { valueStr.toString(), "null Converter" };

            throw new ConverterException(
                    MessageUtils.getExceptionMessage(MessageUtils.CONVERSION_ERROR_MESSAGE_ID, params));
        }
    }

    assert (null != result);
    if (elementType.isPrimitive()) {
        for (int i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])));
            }
        }
    } else {
        for (int i = 0; i < len; i++) {
            if (logger.isLoggable(Level.FINE)) {
                Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]);
                logger.fine("String value: " + newValues[i] + " converts to : " + converted.toString());
            }
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
        }
    }
    return result;

}

From source file:com.jaspersoft.jasperserver.ws.axis2.scheduling.ReportJobBeanTraslator.java

protected Object toCollectionValue(Class parameterType, Object valueArray) {
    Object reportValue;//  ww w.  j  a va 2 s.c o m
    int valueCount = Array.getLength(valueArray);
    if (parameterType.equals(Object.class) || parameterType.equals(Collection.class)
            || parameterType.equals(Set.class)) {
        Collection values = new ListOrderedSet();
        for (int i = 0; i < valueCount; ++i) {
            values.add(Array.get(valueArray, i));
        }
        reportValue = values;
    } else if (parameterType.equals(List.class)) {
        Collection values = new ArrayList(valueCount);
        for (int i = 0; i < valueCount; ++i) {
            values.add(Array.get(valueArray, i));
        }
        reportValue = values;
    } else if (parameterType.isArray()) {
        Class componentType = parameterType.getComponentType();
        if (componentType.equals(valueArray.getClass().getComponentType())) {
            reportValue = valueArray;
        } else {
            reportValue = Array.newInstance(componentType, valueCount);
            for (int i = 0; i < valueCount; ++i) {
                Array.set(reportValue, i, Array.get(valueArray, i));
            }
        }
    } else {
        throw new JSException("report.scheduling.ws.collection.parameter.type.not.supported",
                new Object[] { parameterType.getName() });
    }
    return reportValue;
}

From source file:com.espertech.esper.util.PopulateUtil.java

private static Object coerceProperty(String propertyName, Class containingType, Object value, Class type,
        EngineImportService engineImportService, boolean forceNumeric) throws ExprValidationException {
    if (value instanceof ExprNode && type != ExprNode.class) {
        if (value instanceof ExprIdentNode) {
            ExprIdentNode identNode = (ExprIdentNode) value;
            Property prop;/*from  w  w w .  j  av a  2 s  . com*/
            try {
                prop = PropertyParser.parse(identNode.getFullUnresolvedName(), false);
            } catch (Exception ex) {
                throw new ExprValidationException(
                        "Failed to parse property '" + identNode.getFullUnresolvedName() + "'");
            }
            if (!(prop instanceof MappedProperty)) {
                throw new ExprValidationException(
                        "Unrecognized property '" + identNode.getFullUnresolvedName() + "'");
            }
            MappedProperty mappedProperty = (MappedProperty) prop;
            if (mappedProperty.getPropertyNameAtomic().toLowerCase().equals(SYSTEM_PROPETIES_NAME)) {
                return System.getProperty(mappedProperty.getKey());
            }
        } else {
            ExprNode exprNode = (ExprNode) value;
            ExprEvaluator evaluator = exprNode.getExprEvaluator();
            if (evaluator == null) {
                throw new ExprValidationException(
                        "Failed to evaluate expression '" + exprNode.toExpressionString() + "'");
            }
            value = evaluator.evaluate(null, true, null);
        }
    }

    if (value == null) {
        return null;
    }
    if (value.getClass() == type) {
        return value;
    }
    if (JavaClassHelper.isAssignmentCompatible(value.getClass(), type)) {
        if (forceNumeric && JavaClassHelper.getBoxedType(value.getClass()) != JavaClassHelper.getBoxedType(type)
                && JavaClassHelper.isNumeric(type) && JavaClassHelper.isNumeric(value.getClass())) {
            value = JavaClassHelper.coerceBoxed((Number) value, JavaClassHelper.getBoxedType(type));
        }
        return value;
    }
    if (JavaClassHelper.isSubclassOrImplementsInterface(value.getClass(), type)) {
        return value;
    }
    if (type.isArray()) {
        if (!(value instanceof Collection)) {
            throw new ExprValidationException("Property '" + propertyName + "' of class "
                    + JavaClassHelper.getClassNameFullyQualPretty(containingType)
                    + " expects an array but receives a value of type " + value.getClass().getName());
        }
        Object[] items = ((Collection) value).toArray();
        Object coercedArray = Array.newInstance(type.getComponentType(), items.length);
        for (int i = 0; i < items.length; i++) {
            Object coercedValue = coerceProperty(propertyName + " (array element)", type, items[i],
                    type.getComponentType(), engineImportService, false);
            Array.set(coercedArray, i, coercedValue);
        }
        return coercedArray;
    }
    if (!(value instanceof Map)) {
        throw new ExprValidationException("Property '" + propertyName + "' of class "
                + JavaClassHelper.getClassNameFullyQualPretty(containingType) + " expects an "
                + JavaClassHelper.getClassNameFullyQualPretty(type) + " but receives a value of type "
                + value.getClass().getName());
    }
    Map<String, Object> props = (Map<String, Object>) value;
    return instantiatePopulateObject(props, type, engineImportService);
}