Example usage for java.lang.reflect Array getLength

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static native int getLength(Object array) throws IllegalArgumentException;

Source Link

Document

Returns the length of the specified array object, as an int .

Usage

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF3Serializer.java

protected void writeAMF3Array(Object array) throws IOException {
    if (debugMore)
        debug("writeAMF3Array(array=", array, ")");

    write(AMF3_ARRAY);//from w  ww  . ja  v a 2  s  .  co  m

    int index = indexOfStoredObjects(array);
    if (index >= 0)
        writeAMF3IntegerData(index << 1);
    else {
        addToStoredObjects(array);

        int length = Array.getLength(array);
        writeAMF3IntegerData(length << 1 | 0x01);
        write(0x01);
        for (int i = 0; i < length; i++)
            writeObject(Array.get(array, i));
    }
}

From source file:com.adf.bean.AbsBean.java

private JSONArray arrayObjectToJson(Object val) {
    int count = Array.getLength(val);
    JSONArray arr = new JSONArray();
    for (int i = 0; i < count; i++) {
        Object obj = Array.get(val, i);
        arr.put(obj);/*from  www.  j a  v a 2  s  . c o m*/
    }
    return arr;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), for the specified property.
 * /*from ww  w .  ja v  a  2s.  c  o  m*/
 * @param propertyName
 *            name of the property
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param typeDescriptor
 *            the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType,
        TypeDescriptor typeDescriptor) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException firstAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        TypeDescriptor targetTypeDesc = typeDescriptor;
        if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
            try {
                return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                firstAttemptEx = ex;
            }
        }
    }

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (requiredType != null && Collection.class.isAssignableFrom(requiredType)
                && convertedValue instanceof String) {
            TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
            if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) {
                convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String
                        && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType,
                        typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor strCtor = requiredType.getConstructor(String.class);
                        return (T) BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Construction via String failed for type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (firstAttemptEx != null) {
                throw firstAttemptEx;
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type [")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("]");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (firstAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null
                && !Object.class.equals(requiredType)) {
            throw firstAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
    }

    return (T) convertedValue;
}

From source file:com.bstek.dorado.view.output.JsonBuilder.java

/**
 * /*  ww w  .j  a  v a  2  s .  c om*/
 */
public JsonBuilder value(Object o) {
    if (o == null) {
        outputValue("null", false);
    } else if (o instanceof Number || o instanceof Boolean) {
        if (o instanceof Float && (Float.isNaN((Float) o))) {
            outputValue("undefined", false);
        }
        if (o instanceof Double && (Double.isNaN((Double) o))) {
            outputValue("undefined", false);
        } else {
            outputValue(o.toString(), false);
        }
    } else if (o.getClass().isArray()) {
        array();
        int len = Array.getLength(o);
        for (int i = 0; i < len; i++) {
            value(Array.get(o, i));
        }
        endArray();
    } else {
        String s = o.toString();
        if (s.length() == 0) {
            outputValue("\"\"", false);
        } else {
            outputValue(StringEscapeUtils.escapeJavaScript(s), true);
        }
    }
    return this;
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverter.java

/**
 * Convert any array to {@code List<Object>}
 * @param arrayObject array to convert//w w w.j  a va 2 s. co  m
 * @return list
 */
private static List<Object> arrayObjectToList(final Object arrayObject) {
    // 'arrayObject' must be array
    return new AbstractList<Object>() {
        @Override
        public Object get(int index) {
            return Array.get(arrayObject, index);
        }

        @Override
        public int size() {
            return Array.getLength(arrayObject);
        }
    };
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * <p>Return the size of an indexed or mapped property.</p>
 *
 * @param name Name of the property// w ww. j  a  v  a 2s  .  c o m
 * @return The indexed or mapped property size
 * @exception IllegalArgumentException if no property name is specified
 */
public int size(String name) {

    if (name == null) {
        throw new IllegalArgumentException("No property name specified");
    }

    Object value = values.get(name);
    if (value == null) {
        return 0;
    }

    if (value instanceof Map) {
        return ((Map) value).size();
    }

    if (value instanceof List) {
        return ((List) value).size();
    }

    if ((value.getClass().isArray())) {
        return Array.getLength(value);
    }

    return 0;

}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private XYDataset createXYDataset(double x[], double y[]) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries serie = new XYSeries("Single");
    for (int i = 0; i < Array.getLength(x); i++)
        serie.add(x[i], y[i]);//from  w w  w .jav  a 2 s . c  om

    dataset.addSeries(serie);

    return dataset;
}

From source file:org.apache.openaz.xacml.std.annotations.RequestParser.java

public static Collection<AttributeValue<?>> extractValues(String datatype, Field field, Object object)
        throws IllegalArgumentException, IllegalAccessException, DataTypeException {
    ////from  w w  w  .j a  v a2 s. c om
    // Synchronize?
    //
    DataTypeFactory dtFactory = getDataTypeFactory();
    if (dtFactory == null) {
        logger.error("Could not create data type factory");
        return null;
    }
    //
    // This is what we will return
    //
    Collection<AttributeValue<?>> values = new ArrayList<AttributeValue<?>>();
    //
    // Sanity check the object
    //
    Object fieldObject = field.get(object);
    if (logger.isDebugEnabled()) {
        logger.debug(fieldObject);
    }
    if (fieldObject == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("field's object is null.");
        }
        return values;
    }
    //
    // Are we working with a collection or an array?
    //
    if (field.get(object) instanceof Collection || field.get(object) instanceof Map) {
        Collection<?> objects = (Collection<?>) field.get(object);
        if (objects == null || objects.isEmpty()) {
            if (logger.isTraceEnabled()) {
                logger.trace("empty collection");
            }
            return values;
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Object is a collection");
        }
        for (Object obj : objects) {
            values.add(extractValue(datatype, obj));
        }
    } else if (fieldObject.getClass().isArray()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Object is an array");
        }
        for (int i = 0; i < Array.getLength(fieldObject); i++) {
            values.add(extractValue(datatype, Array.get(fieldObject, i)));
        }
    } else {
        values.add(extractValue(datatype, field.get(object)));
    }
    return values;
}