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:com.bluecloud.ioc.core.KernelComponentDepender.java

/**
 * <h3>?</h3>//from ww w .  j  av  a  2 s.  c  o  m
 * 
 * @param limited
 *            ???
 * @param type
 *            
 * @param size
 *            Component
 * @param services
 *            ??
 * @param context
 *            ??Component?
 * @return
 * @throws KernelComponentDependerException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws SecurityException
 * @throws IllegalArgumentException
 */
private Object haveLimited(String limited, String type, int size, ServicesMetadata services,
        ComponentContext context) throws KernelComponentDependerException, IllegalArgumentException,
        SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        InvocationTargetException, NoSuchMethodException {
    Class<?> limitedClass = (Class<?>) ClassHandler.getClass(limited, false);
    if (type.equals("List")) {
        return this.collectionType(new ArrayList<Object>(size), services, context, limitedClass, limited);
    }
    if (type.equals("Set")) {
        return this.collectionType(new HashSet<Object>(size), services, context, limitedClass, limited);
    }
    if (type.equals("Map")) {
        Map<Object, Object> map = new HashMap<Object, Object>(size);
        for (ServiceMetadata service : services.getServices()) {
            Object serviceObject = this.getServiceDepend(service, context);
            if (limitedClass.isAssignableFrom(serviceObject.getClass())) {
                if (service.getName() != null) {
                    map.put(service.getName(), serviceObject);
                } else if (service.getName() == null && service.getBind() != null) {
                    map.put(service.getBind(), serviceObject);
                }
            } else {
                if (log.isErrorEnabled()) {
                    log.error("?" + limited);
                }
                throw new ClassCastException(service.getClazz());
            }
        }
        return map;
    }
    if (type.equals("Array")) {
        Object array = Array.newInstance(limitedClass, size);
        int index = 0;
        for (ServiceMetadata service : services.getServices()) {
            Object serviceObject = this.getServiceDepend(service, context);
            if (limitedClass.isAssignableFrom(serviceObject.getClass())) {
                Array.set(array, index, serviceObject);
                index++;
            } else {
                if (log.isErrorEnabled()) {
                    log.error("?" + limited);
                }
                throw new ClassCastException(service.getClazz());
            }
        }
        return array;
    }
    return null;
}

From source file:ArrayUtils.java

/**
 * Merges elements found in each of a set of arrays into a single array with
 * no duplicates. For primitive types./*from  ww w. j a  va  2  s .  c  om*/
 * 
 * @param type
 *            The type of the result
 * @param arrays
 *            The arrays to merge
 * @return A new array containing all common elements between
 *         <code>array1</code> and <code>array2</code>
 * @throws NullPointerException
 *             If either array is null
 * @throws ArrayStoreException
 *             If elements in the arrays are incompatible with
 *             <code>type</code>
 */
public static Object mergeExclusiveP(Class<?> type, Object... arrays) {
    if (arrays.length == 0)
        return Array.newInstance(type, 0);
    java.util.ArrayList<Object> retSet = new java.util.ArrayList<Object>();
    int i, j, k;
    int len = Array.getLength(arrays[0]);
    for (j = 0; j < len; j++)
        retSet.add(Array.get(arrays[0], j));
    for (i = 1; i < arrays.length; i++) {
        for (j = 0; j < retSet.size(); j++) {
            len = Array.getLength(arrays[i]);
            boolean hasEl = false;
            for (k = 0; k < len; k++)
                if (equalsUnordered(retSet.get(j), Array.get(arrays[i], k))) {
                    hasEl = true;
                    break;
                }
            if (!hasEl) {
                retSet.remove(j);
                j--;
            }
        }
    }
    Object ret = Array.newInstance(type, retSet.size());
    for (i = 0; i < retSet.size(); i++)
        Array.set(ret, i, retSet.get(i));
    return ret;
}

From source file:org.cosmo.common.record.Defn.java

public Object readAll(int maxCounts) throws IOException {
    int count = Math.min(readCount(), maxCounts);
    byte[] buf = readFullRawBytes(maxCounts).array();
    ByteBuffer readDataIO = ByteBuffer.allocate(size());
    Object elements = null;// w ww .  ja va  2 s. co m

    if (this instanceof DefnRecord) {
        elements = Array.newInstance(long.class, count);
        for (int i = 0, offset = 0, size = size(), c = count; i < c; i++, offset += size) {
            readDataIO.put(buf, offset, size);
            readDataIO.rewind();
            readDataIO.get(); // skip header byte
            Array.set(elements, i, readDataIO.getLong());
            readDataIO.rewind();
        }
    } else {
        elements = Array.newInstance(field().getType(), count);
        for (int i = 0, offset = 0, size = size(), c = count; i < c; i++, offset += size) {
            readDataIO.put(buf, offset, size);
            readDataIO.rewind();
            readDataIO.get(); // skip header byte
            Array.set(elements, i, readImpl(readDataIO, false));
            readDataIO.rewind();
        }
    }

    return elements;
}

From source file:javadz.beanutils.locale.LocaleConvertUtilsBean.java

/**
 * Convert an array of specified values to an array of objects of the
 * specified class (if possible) using the convertion pattern.
 *
 * @param values Value to be converted (may be null)
 * @param clazz Java array or element class to be converted to
 * @param locale The locale/*w  w  w . ja  va2s. com*/
 * @param pattern The convertion pattern
 * @return the converted value
 *
 * @throws org.apache.commons.beanutils.ConversionException if thrown by an
 * underlying Converter
 */
public Object convert(String[] values, Class clazz, Locale locale, String pattern) {

    Class type = clazz;
    if (clazz.isArray()) {
        type = clazz.getComponentType();
    }
    if (log.isDebugEnabled()) {
        log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using " + locale
                + " locale and " + pattern + " pattern");
    }

    Object array = Array.newInstance(type, values.length);
    for (int i = 0; i < values.length; i++) {
        Array.set(array, i, convert(values[i], type, locale, pattern));
    }

    return (array);
}

From source file:org.springframework.beans.AbstractNestablePropertyAccessor.java

@SuppressWarnings("unchecked")
private void processKeyedProperty(PropertyTokenHolder tokens, PropertyValue pv) {
    Object propValue = getPropertyHoldingValue(tokens);
    PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
    if (ph == null) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.actualName,
                "No property handler found");
    }//from  ww  w.j  a va2s  .c om
    Assert.state(tokens.keys != null, "No token keys");
    String lastKey = tokens.keys[tokens.keys.length - 1];

    if (propValue.getClass().isArray()) {
        Class<?> requiredType = propValue.getClass().getComponentType();
        int arrayIndex = Integer.parseInt(lastKey);
        Object oldValue = null;
        try {
            if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                oldValue = Array.get(propValue, arrayIndex);
            }
            Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                    requiredType, ph.nested(tokens.keys.length));
            int length = Array.getLength(propValue);
            if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) {
                Class<?> componentType = propValue.getClass().getComponentType();
                Object newArray = Array.newInstance(componentType, arrayIndex + 1);
                System.arraycopy(propValue, 0, newArray, 0, length);
                setPropertyValue(tokens.actualName, newArray);
                propValue = getPropertyValue(tokens.actualName);
            }
            Array.set(propValue, arrayIndex, convertedValue);
        } catch (IndexOutOfBoundsException ex) {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                    "Invalid array index in property path '" + tokens.canonicalName + "'", ex);
        }
    }

    else if (propValue instanceof List) {
        Class<?> requiredType = ph.getCollectionType(tokens.keys.length);
        List<Object> list = (List<Object>) propValue;
        int index = Integer.parseInt(lastKey);
        Object oldValue = null;
        if (isExtractOldValueForEditor() && index < list.size()) {
            oldValue = list.get(index);
        }
        Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(), requiredType,
                ph.nested(tokens.keys.length));
        int size = list.size();
        if (index >= size && index < this.autoGrowCollectionLimit) {
            for (int i = size; i < index; i++) {
                try {
                    list.add(null);
                } catch (NullPointerException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                            "Cannot set element with index " + index + " in List of size " + size
                                    + ", accessed using property path '" + tokens.canonicalName
                                    + "': List does not support filling up gaps with null elements");
                }
            }
            list.add(convertedValue);
        } else {
            try {
                list.set(index, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                        "Invalid list index in property path '" + tokens.canonicalName + "'", ex);
            }
        }
    }

    else if (propValue instanceof Map) {
        Class<?> mapKeyType = ph.getMapKeyType(tokens.keys.length);
        Class<?> mapValueType = ph.getMapValueType(tokens.keys.length);
        Map<Object, Object> map = (Map<Object, Object>) propValue;
        // IMPORTANT: Do not pass full property name in here - property editors
        // must not kick in for map keys but rather only for map values.
        TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
        Object convertedMapKey = convertIfNecessary(null, null, lastKey, mapKeyType, typeDescriptor);
        Object oldValue = null;
        if (isExtractOldValueForEditor()) {
            oldValue = map.get(convertedMapKey);
        }
        // Pass full property name and old value in here, since we want full
        // conversion ability for map values.
        Object convertedMapValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                mapValueType, ph.nested(tokens.keys.length));
        map.put(convertedMapKey, convertedMapValue);
    }

    else {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                "Property referenced in indexed property path '" + tokens.canonicalName
                        + "' is neither an array nor a List nor a Map; returned value was [" + propValue + "]");
    }
}

From source file:meizhi.meizhi.malin.utils.DestroyCleanUtil.java

/**
 * Hack TextLine//w  ww .  j  a v a 2  s  .co m
 * http://stackoverflow.com/questions/30397356/android-memory-leak-on-textview-leakcanary-leak-can-be-ignored
 * https://github.com/square/leakcanary/blob/master/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidExcludedRefs.java
 * fix https://github.com/android/platform_frameworks_base/commit/b3a9bc038d3a218b1dbdf7b5668e3d6c12be5ee4
 * <p>
 * blog:
 * http://snzang.leanote.com/post/c321f719cd02
 */
public static void fixTextLineCacheLeak() {
    //if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) return;
    try {
        Field textLineCached;
        textLineCached = Class.forName("android.text.TextLine").getDeclaredField("sCached");
        if (textLineCached == null)
            return;
        textLineCached.setAccessible(true);

        // Get reference to the TextLine sCached array.
        Object cached = textLineCached.get(null);
        if (cached == null)
            return;
        // Clear the array.
        for (int i = 0, size = Array.getLength(cached); i < size; i++) {
            Array.set(cached, i, null);
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:org.jdesigner.platform.web.converter.ArrayConverter.java

/**
 * Handles conversion to an array of the specified type.
 * /*from  w ww  .  j av  a 2s.  c  o  m*/
 * @param type
 *            The type to which this value should be converted.
 * @param value
 *            The input value to be converted.
 * @return The converted value.
 * @throws Throwable
 *             if an error occurs converting to the specified type
 */
protected Object convertToType(Class type, Object value) throws Throwable {

    if (!type.isArray()) {
        throw new ConversionException(
                toString(getClass()) + " cannot handle conversion to '" + toString(type) + "' (not an array).");
    }

    // Handle the source
    int size = 0;
    Iterator iterator = null;
    if (value.getClass().isArray()) {
        size = Array.getLength(value);
    } else {
        Collection collection = convertToCollection(type, value);
        size = collection.size();
        iterator = collection.iterator();
    }

    // Allocate a new Array
    Class componentType = type.getComponentType();
    Object newArray = Array.newInstance(componentType, size);

    // Convert and set each element in the new Array
    for (int i = 0; i < size; i++) {
        Object element = iterator == null ? Array.get(value, i) : iterator.next();
        // - probably should catch conversion errors and throw
        // new exception providing better info back to the user
        element = elementConverter.convert(componentType, element);
        Array.set(newArray, i, element);
    }

    return newArray;
}

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

/**
 * Creates a java array from a JSONArray.<br>
 *///from w  w w  .ja  v a2  s.  c o  m
public static Object toArray(JSONArray jsonArray, JsonConfig jsonConfig) {
    Class objectClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (jsonArray.size() == 0) {
        return Array.newInstance(objectClass == null ? Object.class : 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, objectClass, classMap));
            } else if (String.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(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 if (JSONUtils.isNumber(type)) {
                if (objectClass != null && (Byte.class.isAssignableFrom(objectClass)
                        || Byte.TYPE.isAssignableFrom(objectClass))) {
                    Array.set(array, i, Byte.valueOf(String.valueOf(value)));
                } else if (objectClass != null && (Short.class.isAssignableFrom(objectClass)
                        || Short.TYPE.isAssignableFrom(objectClass))) {
                    Array.set(array, i, Short.valueOf(String.valueOf(value)));
                } else {
                    Array.set(array, i, value);
                }
            } else {
                if (objectClass != null) {
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(objectClass);
                    jsc.setClassMap(classMap);
                    Array.set(array, i, JSONObject.toBean((JSONObject) value, jsc));
                } else {
                    Array.set(array, i, JSONObject.toBean((JSONObject) value));
                }
            }
        }
    }
    return array;
}

From source file:com.sun.faces.renderkit.html_basic.MenuRenderer.java

protected Object handleArrayCase(FacesContext context, UISelectMany uiSelectMany, Class arrayClass,
        String[] newValues) throws ConverterException {
    Object result = null;/*from  ww  w . ja  v a 2 s. co  m*/
    Class elementType = null;
    Converter converter = null;
    int i = 0, len = (null != newValues ? newValues.length : 0);

    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;
            }
            String valueStr = "";
            for (i = 0; i < newValues.length; i++) {
                valueStr = valueStr + " " + newValues[i];
            }
            Object[] params = { valueStr, "null Converter" };

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

    Util.doAssert(null != result);
    if (elementType.isPrimitive()) {
        for (i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])).booleanValue());
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i,
                        ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])).byteValue());
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])).doubleValue());
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i,
                        ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])).floatValue());
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i,
                        ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])).intValue());
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])).charValue());
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i,
                        ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])).shortValue());
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i,
                        ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])).longValue());
            }
        }
    } else {
        for (i = 0; i < len; i++) {
            if (log.isDebugEnabled()) {
                Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]);
                log.debug("String value: " + newValues[i] + " converts to : " + converted.toString());
            }
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
        }
    }
    return result;
}

From source file:net.jofm.DefaultFixedMapper.java

private void fromFixedFieldList(Object destinationObject, StringBuilder line,
        FixedFieldListMetaData fixedFieldListMetaData) throws Exception {
    String savedLine = line.toString();

    PrimitiveFieldMetaData counterFieldMetaData = fixedFieldListMetaData.getCounterFieldMetaData();
    int counterLength = counterFieldMetaData.getLength();
    Object[] arrayFieldValue = null;
    if (counterLength > 0) {
        String counterData = read(line, counterLength);
        int counter = (Integer) counterFieldMetaData.getFormatter().parse(counterData, int.class);
        arrayFieldValue = (Object[]) Array.newInstance(fixedFieldListMetaData.getComponentType(), counter);
        for (int i = 0; i < counter; i++) {
            Object fieldValue = fromFixedField(line, fixedFieldListMetaData.getFieldMetaData(),
                    fixedFieldListMetaData.getComponentType());
            Array.set(arrayFieldValue, i, fieldValue);
        }//  www.j  a  va2s. c  o m
    } else {
        List<Object> objectList = new ArrayList<Object>();

        Object fieldValue = null;
        do {
            fieldValue = fromFixedField(line, fixedFieldListMetaData.getFieldMetaData(),
                    fixedFieldListMetaData.getComponentType());

            if (fieldValue != null) {
                objectList.add(fieldValue);
            }
        } while (fieldValue != null);

        arrayFieldValue = (Object[]) Array.newInstance(fixedFieldListMetaData.getComponentType(),
                objectList.size());
        arrayFieldValue = objectList.toArray(arrayFieldValue);
    }

    String readData = savedLine.substring(0, savedLine.length() - line.length());
    setProperty(destinationObject, fixedFieldListMetaData.getField().getName(), readData, arrayFieldValue,
            fixedFieldListMetaData.isIgnored());
}