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.heliosapm.opentsdb.client.jvmjmx.custom.aggregation.AggregateFunction.java

/**
 * Computes and returns the aggregate for the named aggregator and object of nput items.
 * The object is introspected to determine if it is:<ul>
 *  <li>Null</li>//from w w w .  ja v a  2  s . c  om
 *    <li>{@link java.util.Map}</li>
 *    <li>{@link java.util.Collection}</li>
 *    <li>An array</li>
 * </ul>.
 * If it is none of the above, a runtime exception is thrown.
 * If it is a map or an array, it is converted to a list for aggregate computation.
 * @param name The name of the aggregator function
 * @param item The object of items to aggregate
 * @return the aggregate value
 * TODO:  Do we need to support multi dimmensional arrays ?
 */
@SuppressWarnings("unchecked")
public static Object aggregate(CharSequence name, Object item) {
    final List<Object> items;
    final AggregateFunction function = AggregateFunction.forName(name);
    if (item == null) {
        items = Collections.EMPTY_LIST;
    } else if (item instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) item;
        items = new ArrayList<Object>(map.keySet());
    } else if (item instanceof Collection) {
        items = new ArrayList<Object>((Collection<Object>) item);
    } else if (item.getClass().isArray()) {
        int length = Array.getLength(item);
        items = new ArrayList<Object>(length);
        for (int i = 0; i < length; i++) {
            items.add(i, Array.get(item, i));
        }
    } else {
        throw new IllegalArgumentException("Aggregate object of type [" + item.getClass().getName()
                + "] was not a Map, Collection or Array", new Throwable());
    }
    return function.aggregate(items);
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Remove the index'th element from the supplied collection.
 * @param collection to edit/*from  ww  w  .  j  a  v  a2 s. co  m*/
 * @param index int
 * @return the resulting collection
 */
public static Object remove(Object collection, int index) {
    collection = getValue(collection);
    if (collection == null) {
        return null;
    }
    if (index >= getLength(collection)) {
        throw new JXPathException("No such element at index " + index);
    }
    if (collection.getClass().isArray()) {
        int length = Array.getLength(collection);
        Object smaller = Array.newInstance(collection.getClass().getComponentType(), length - 1);
        if (index > 0) {
            System.arraycopy(collection, 0, smaller, 0, index);
        }
        if (index < length - 1) {
            System.arraycopy(collection, index + 1, smaller, index, length - index - 1);
        }
        return smaller;
    }
    if (collection instanceof List) {
        int size = ((List) collection).size();
        if (index < size) {
            ((List) collection).remove(index);
        }
        return collection;
    }
    if (collection instanceof Collection) {
        Iterator it = ((Collection) collection).iterator();
        for (int i = 0; i < index; i++) {
            if (!it.hasNext()) {
                break;
            }
            it.next();
        }
        if (it.hasNext()) {
            it.next();
            it.remove();
        }
        return collection;
    }
    throw new JXPathException("Cannot remove " + collection.getClass().getName() + "[" + index + "]");
}

From source file:org.apache.axis.utils.BeanPropertyDescriptor.java

/**
 * Grow the array /*from  w w  w  .ja  v a2 s.c o  m*/
 * @param obj
 * @param componentType
 * @param i
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
protected void growArrayToSize(Object obj, Class componentType, int i)
        throws InvocationTargetException, IllegalAccessException {
    // Get the entire array and make sure it is large enough
    Object array = get(obj);
    if (array == null || Array.getLength(array) <= i) {
        // Construct a larger array of the same type            
        Object newArray = Array.newInstance(componentType, i + 1);
        // Copy over the old elements
        if (array != null) {
            System.arraycopy(array, 0, newArray, 0, Array.getLength(array));
        }
        // Set the object to use the larger array
        set(obj, newArray);
    }
}

From source file:org.bbreak.excella.reports.util.ReportsUtil.java

/**
 * ?????????????<BR>/*from   ww w  .  jav a 2  s .c om*/
 * 
 * <pre>
 * ?
 * ??:???
 * 
 * $R[]:?
 * $C:
 * $:???
 * ??????????:????$:???  
 * 
 * ($BR[]?$BC[])?.????
 * ?????
 * ??:???.??:???.??:???
 * 
 * $BR[]:.$R[]:
 * $BR[]:.??
 * </pre>
 * 
 * @param info 
 * @param propertyNameString ?
 * @param parsers ?
 * @return ????
 */
public static List<Object> getParamValues(ParamInfo info, String propertyNameString,
        List<ReportsTagParser<?>> parsers) {

    String[] levels = propertyNameString.split("\\.");

    List<Object> paramValues = new ArrayList<Object>();

    ParamInfo[] paramInfos = new ParamInfo[] { info };
    for (String level : levels) {

        String tagName = null;
        String propertyName = null;
        if (level.indexOf(":") != -1) {
            // ?
            String[] values = level.split(":");
            tagName = values[0];
            propertyName = values[1];
        } else {
            // ??????
            tagName = SingleParamParser.DEFAULT_TAG;
            propertyName = level;
        }

        List<SingleParamParser> singleParsers = new ArrayList<SingleParamParser>();
        for (ReportsTagParser<?> reportsParser : parsers) {
            if (reportsParser instanceof SingleParamParser) {
                singleParsers.add((SingleParamParser) reportsParser);
            }
        }

        // ????
        ReportsTagParser<?> targetParser = null;
        for (ReportsTagParser<?> tagParser : parsers) {
            if (tagParser.getTag().equals(tagName)) {
                targetParser = tagParser;
            }
        }
        if (targetParser == null) {
            // ??
            break;
        }

        // ??
        Object object = null;
        for (ParamInfo paramInfo : paramInfos) {
            object = targetParser.getParamData(paramInfo, propertyName);
            if (object != null) {
                break;
            }
        }

        if (object != null) {
            if (object instanceof ParamInfo[]) {
                // $BR[],$BC[]
                List<ParamInfo> newParamInfos = new ArrayList<ParamInfo>();
                for (ParamInfo paramInfo : paramInfos) {
                    ParamInfo[] params = (ParamInfo[]) targetParser.getParamData(paramInfo, propertyName);
                    if (params != null) {
                        newParamInfos.addAll(Arrays.asList(params));
                    }
                }
                paramInfos = newParamInfos.toArray(new ParamInfo[newParamInfos.size()]);
            } else if (object.getClass().isArray()) {
                if (Array.getLength(object) == 0) {
                    continue;
                }

                if (Array.get(object, 0) instanceof String || Array.get(object, 0) instanceof Number
                        || Array.get(object, 0) instanceof Date || Array.get(object, 0) instanceof Boolean) {
                    // $R[],$C[]
                    for (ParamInfo paramInfo : paramInfos) {
                        Object arrayObj = targetParser.getParamData(paramInfo, propertyName);
                        if (arrayObj != null) {
                            for (int i = 0; i < Array.getLength(arrayObj); i++) {
                                paramValues.add(Array.get(arrayObj, i));
                            }
                        }
                    }
                } else {
                    // $BR[],$BC[]
                    List<ParamInfo> newParamInfos = new ArrayList<ParamInfo>();
                    for (ParamInfo paramInfo : paramInfos) {
                        Object[] params = (Object[]) targetParser.getParamData(paramInfo, propertyName);

                        // POJOParamInfo???
                        for (Object obj : params) {
                            if (obj instanceof ParamInfo) {
                                newParamInfos.add((ParamInfo) obj);
                                continue;
                            }
                            ParamInfo childParamInfo = new ParamInfo();

                            Map<String, Object> map = null;
                            try {
                                map = PropertyUtils.describe(obj);
                            } catch (Exception e) {
                                throw new RuntimeException(
                                        "????????", e);
                            }
                            for (Map.Entry<String, Object> entry : map.entrySet()) {
                                for (ReportsTagParser<?> parser : singleParsers) {
                                    childParamInfo.addParam(parser.getTag(), entry.getKey(), entry.getValue());
                                }
                            }
                            newParamInfos.add(childParamInfo);
                        }
                    }
                    paramInfos = newParamInfos.toArray(new ParamInfo[newParamInfos.size()]);
                }

            } else if (object instanceof Collection<?>) {
                for (ParamInfo paramInfo : paramInfos) {
                    Collection<?> collection = (Collection<?>) targetParser.getParamData(paramInfo,
                            propertyName);
                    if (collection != null) {
                        paramValues.addAll(collection);
                    }
                }
            } else {
                // $,$I
                for (ParamInfo paramInfo : paramInfos) {
                    Object value = targetParser.getParamData(paramInfo, propertyName);
                    if (value != null) {
                        paramValues.add(value);
                    }
                }

            }
        }

    }

    return paramValues;

}

From source file:de.tuberlin.uebb.jbop.optimizer.array.ArrayHelper.java

/**
 * Gets the length.//from   w  ww.j  a  v a  2  s  . c  om
 * 
 * @param instance
 *          the instance
 * @return the length
 * @throws JBOPClassException
 *           the jBOP class exception
 */
int getLength(final Object instance) throws JBOPClassException {
    try {
        return Array.getLength(getValue(instance));
    } catch (final IllegalArgumentException iae) {
        throw new JBOPClassException("Arraylength could not be determined.", iae);
    }
}

From source file:com.jskaleel.xml.JSONArray.java

/**
 * Construct a JSONArray from an array/*ww  w. j a  va 2  s.c o  m*/
 *
 * @throws JSONException
 *             If not an array.
 */
public JSONArray(Object array) throws JSONException {
    this();
    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        for (int i = 0; i < length; i += 1) {
            this.put(JSONObject.wrap(Array.get(array, i)));
        }
    } else {
        throw new JSONException("JSONArray initial value should be a string or collection or array.");
    }
}

From source file:ArraysX.java

/**
 * Duplicates the specified array./*ww w.  ja va 2s .c om*/
 * @param ary the array
 * @return an array duplicated from ary
 * @exception IllegalArgumentException if ary is not any array
 * @exception IndexOutOfBoundsException if out of bounds
 */
public static final Object duplicate(Object ary) {
    return duplicate(ary, 0, Array.getLength(ary));
}

From source file:com.examples.with.different.packagename.testcarver.AbstractConverter.java

/**
 * Return the first element from an Array (or Collection)
 * or the value unchanged if not an Array (or Collection).
 *
 * N.B. This needs to be overriden for array/Collection converters.
 *
 * @param value The value to convert/*from w  w w  .  ja  va2  s . c  o  m*/
 * @return The first element in an Array (or Collection)
 * or the value unchanged if not an Array (or Collection)
 */
protected Object convertArray(Object value) {
    if (value == null) {
        return null;
    }
    if (value.getClass().isArray()) {
        if (Array.getLength(value) > 0) {
            return Array.get(value, 0);
        } else {
            return null;
        }
    }
    if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (collection.size() > 0) {
            return collection.iterator().next();
        } else {
            return null;
        }
    }
    return value;
}

From source file:org.ajax4jsf.builder.mojo.CompileMojo.java

/**
 * Convert any Java Object to JavaScript representation ( as possible ).
 * /*from w ww . j  av  a  2 s  .  co m*/
 * @param obj
 * @return
 * @throws MojoExecutionException
 */
public String toLog(Object obj) throws MojoExecutionException {
    if (null == obj) {
        return "null";
    } else if (obj.getClass().isArray()) {
        StringBuffer ret = new StringBuffer("[");
        boolean first = true;
        for (int i = 0; i < Array.getLength(obj); i++) {
            Object element = Array.get(obj, i);
            if (!first) {
                ret.append(',');
            }
            ret.append(toLog(element));
            first = false;
        }
        return ret.append("]\n").toString();
    } else if (obj instanceof Collection) {
        // Collections put as JavaScript array.
        Collection collection = (Collection) obj;
        StringBuffer ret = new StringBuffer("[");
        boolean first = true;
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (!first) {
                ret.append(',');
            }
            ret.append(toLog(element));
            first = false;
        }
        return ret.append("]\n").toString();
    } else if (obj instanceof Map) {
        // Maps put as JavaScript hash.
        Map map = (Map) obj;

        StringBuffer ret = new StringBuffer("{");
        boolean first = true;
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            Object key = (Object) iter.next();
            if (!first) {
                ret.append(',');
            }
            ret.append(key);
            ret.append(":");
            ret.append(toLog(map.get(key)));
            first = false;
        }
        return ret.append("}\n").toString();
    } else if (obj instanceof Number || obj instanceof Boolean) {
        // numbers and boolean put as-is, without conversion
        return obj.toString();
    } else if (obj instanceof String) {
        // all other put as encoded strings.
        StringBuffer ret = new StringBuffer();
        addEncodedString(ret, obj);
        return ret.append("\n").toString();
    }
    // All other objects threaded as Java Beans.
    try {
        StringBuffer ret = new StringBuffer("{");
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);
        boolean first = true;
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            String key = propertyDescriptor.getName();
            if ("class".equals(key) || propertyDescriptor.getReadMethod() == null) {
                continue;
            }
            if (!first) {
                ret.append(",\n\t");
            }
            addEncodedString(ret, key);
            ret.append(":");
            try {
                ret.append(String.valueOf(PropertyUtils.getProperty(obj, key)));

            } catch (InvocationTargetException e) {
                ret.append("Not ACCESIBLE");
            } // ret.append(toLog(PropertyUtils.getProperty(obj, key)));
            first = false;
        }
        return ret.append("}\n").toString();
    } catch (Exception e) {
        throw new MojoExecutionException("Error in conversion Java Object to String", e);
    }
}

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  . java2  s.  co  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;
}