Example usage for java.lang.reflect Array get

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

Introduction

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

Prototype

public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Returns the value of the indexed component in the specified array object.

Usage

From source file:org.janusgraph.diskstorage.es.ElasticSearchSetup.java

static void applySettingsFromJanusGraphConf(ImmutableSettings.Builder settings, Configuration config,
        ConfigNamespace rootNS) {/*from  w  ww .j ava 2 s .c  om*/
    int keysLoaded = 0;
    Map<String, Object> configSub = config.getSubset(rootNS);
    for (Map.Entry<String, Object> entry : configSub.entrySet()) {
        String key = entry.getKey();
        Object val = entry.getValue();
        if (null == val)
            continue;
        if (List.class.isAssignableFrom(val.getClass())) {
            // Pretty print lists using comma-separated values and no surrounding square braces for ES
            List l = (List) val;
            settings.put(key, Joiner.on(",").join(l));
        } else if (val.getClass().isArray()) {
            // As with Lists, but now for arrays
            // The Object copy[] business lets us avoid repetitive primitive array type checking and casting
            Object copy[] = new Object[Array.getLength(val)];
            for (int i = 0; i < copy.length; i++) {
                copy[i] = Array.get(val, i);
            }
            settings.put(key, Joiner.on(",").join(copy));
        } else {
            // Copy anything else unmodified
            settings.put(key, val.toString());
        }
        log.debug("[ES ext.* cfg] Set {}: {}", key, val);
        keysLoaded++;
    }
    log.debug("Loaded {} settings from the {} JanusGraph config namespace", keysLoaded, rootNS);
}

From source file:de.jgoldhammer.alfresco.jscript.jmx.JmxDumpUtil.java

/**
 * Outputs a single value, dealing with nested arrays and CompositeData
 * objects.//from   ww w .j  a  v  a 2  s  . co  m
 * 
 * @param out
 *            PrintWriter to write the output to
 * @param value
 *            the value to output
 * @param nestLevel
 *            the nesting level
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void outputValue(PrintWriter out, Object value, int nestLevel) throws IOException {
    if (value == null) {
        out.println(JmxDumpUtil.NULL_VALUE);
    } else if (value.getClass().isArray()) {
        int length = Array.getLength(value);
        if (length == 0) {
            out.println("[]");
        } else {
            out.println();
            indent(out, nestLevel + 1);
            out.println('[');
            for (int i = 0; i < length; i++) {
                indent(out, nestLevel + 2);
                outputValue(out, Array.get(value, i), nestLevel + 2);
                if (i + 1 < length) {
                    indent(out, nestLevel + 1);
                    out.println(',');
                }
            }
            indent(out, nestLevel + 1);
            out.println(']');
        }
    } else if (value instanceof CompositeData) {
        out.println();
        indent(out, nestLevel + 1);
        out.println('[');
        printCompositeInfo((CompositeData) value, out, nestLevel + 2);
        indent(out, nestLevel + 1);
        out.println(']');
    } else {
        out.println(value.toString());
    }
}

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.//w w w .  j  a v a  2 s  .c  o  m
 * 
 * @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.jaxygen.converters.properties.PropertiesToBeanConverter.java

private static Object resizeArray(Object array, int size) {
    Object newArray = Array.newInstance(array.getClass().getComponentType(), size);
    for (int i = 0; i < Array.getLength(array); i++) {
        Object value = Array.get(array, i);
        Array.set(newArray, i, value);
    }//from w w  w  .  ja  v  a2s  . c o m
    return newArray;
}

From source file:org.jgentleframework.core.interceptor.AnnotationAroundAdviceMethodInterceptor.java

/**
 * Hash code.//from w  w w  .  j  a  va  2 s. c o m
 * 
 * @param proxy
 *            the proxy
 * @return the int
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
protected int hashCode(Object proxy)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Method[] methods = targetClass.getDeclaredMethods();
    int hashCode = 0;
    for (Method method : methods) {
        Class<?> type = method.getReturnType();
        Object value = (Object) this.attributesMapping.get(method);
        if (value == null)
            value = method.getDefaultValue();
        // if type is primitive type
        if (type.isPrimitive()) {
            // //////////////////////////////////
            // //////////////////////////////////
            hashCode += 127 * method.getName().hashCode() ^ value.hashCode();
        } else if (type.isArray()) {
            Object array = method.invoke(proxy);
            Class<?> comtype = type.getComponentType();
            if (comtype == byte.class || comtype == Byte.class) {
                byte[] valueArr = new byte[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getByte(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == char.class || comtype == Character.class) {
                char[] valueArr = new char[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getChar(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == double.class || comtype == Double.class) {
                double[] valueArr = new double[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getDouble(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == float.class || comtype == Float.class) {
                float[] valueArr = new float[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getFloat(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == int.class || comtype == Integer.class) {
                int[] valueArr = new int[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getInt(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == long.class || comtype == Long.class) {
                long[] valueArr = new long[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getLong(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == short.class || comtype == Short.class) {
                short[] valueArr = new short[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getShort(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else if (comtype == boolean.class || comtype == Boolean.class) {
                boolean[] valueArr = new boolean[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.getBoolean(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            } else {
                Object[] valueArr = new Object[Array.getLength(array)];
                for (int i = 0; i < valueArr.length; i++) {
                    valueArr[i] = Array.get(array, i);
                }
                hashCode += 127 * method.getName().hashCode() ^ Arrays.hashCode(valueArr);
            }
        } else {
            // Object value = method.invoke(proxy);
            hashCode += 127 * method.getName().hashCode() ^ value.hashCode();
        }
    }
    return hashCode;
}

From source file:org.dcm4chee.archive.conf.defaults.DeepEquals.java

/**
 * Deeply compare to Arrays []. Both arrays must be of the same type, same length, and all
 * elements within the arrays must be deeply equal in order to return true.
 * @param dualKey arrays/* w w w .j  a v  a 2 s. c  o m*/
 * @param stack add items to compare to the Stack (Stack versus recursion)
 * @param visited Set of objects already compared (prevents cycles)
 * @return true if the two arrays are the same length and contain deeply equivalent items.
 */
private static boolean compareArrays(DualKey dualKey, LinkedList stack, Set visited) {

    Object array1 = dualKey._key1;
    Object array2 = dualKey._key2;

    // Same instance check already performed...
    int len = Array.getLength(array1);
    if (len != Array.getLength(array2)) {
        return false;
    }

    // try sorting

    //        if (len >0 ) {
    //           if (Array.get(array1, 0) instanceof Comparable)
    //           {
    //
    //              Class<?> c = Array.get(array1, 0).getClass();
    //
    //              if (ClassUtils.isPrimitiveOrWrapper(c))
    //              {
    //               /*   Arrays.sort(array1);
    //                    Arrays.sort((Object[]) array2);*/
    //
    //              } else {
    //
    //              Arrays.sort((Object[]) array1);
    //                Arrays.sort((Object[]) array2);
    //              }
    //
    //           }
    //        }

    for (int i = 0; i < len; i++) {
        DualKey dk = new DualKey(Array.get(array1, i), Array.get(array2, i), Integer.toString(i), dualKey);
        if (!visited.contains(dk)) { // push contents for further comparison
            stack.addFirst(dk);
        }
    }
    return true;
}

From source file:org.springmodules.validation.bean.BeanValidator.java

/**
 * Validates the elements of the given array property.
 *
 * @param root The root of the object graph that is being validated.
 * @param array The given array.//  www. jav a  2 s  . c om
 * @param propertyName The name of the array property.
 * @param errors The {@link Errors} instance where all validation errors will be registered.
 * @param validatedObjects A registry of all objects that were already validated.
 */
protected void validateArrayProperty(Object root, Object array, String propertyName, Errors errors,
        Set validatedObjects) {

    for (int i = 0; i < Array.getLength(array); i++) {
        String nestedPath = propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX;
        errors.pushNestedPath(nestedPath);
        validateObjectGraphConstraints(root, Array.get(array, i), errors, validatedObjects);
        errors.popNestedPath();
    }
}

From source file:adams.ml.Dataset.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < count(); i++) {
        DataRow dr = get(i);/*from w ww . ja  v a 2 s .  c o  m*/
        for (String s : dr.getKeys()) {
            Object o = dr.getObject(s);
            if (o != null && o.getClass().isArray()) {
                sb.append("(" + s + ":");
                for (int j = 0; j < Array.getLength(o); j++) {
                    Object p = Array.get(o, j);
                    sb.append(p.toString());
                    if (j < Array.getLength(o) - 1) {
                        sb.append(",");
                    }
                }
                sb.append(")");
            } else if (o != null) {
                sb.append("(" + s + ":" + o.toString() + ")");
            }
        }
        sb.append("\n");
    }
    return (sb.toString());
}

From source file:cz.vse.esper.XMLRenderer.java

private static void recursiveRender(EventBean theEvent, StringBuilder buf, int level, RendererMeta meta,
        RendererMetaOptions rendererMetaOptions) {
    GetterPair[] simpleProps = meta.getSimpleProperties();
    for (GetterPair simpleProp : simpleProps) {
        Object value = simpleProp.getGetter().get(theEvent);

        if (value == null) {
            continue;
        }/*from   w w w.  j  a v a 2  s.  c  om*/

        ident(buf, level);
        buf.append('<');
        buf.append(simpleProp.getName());
        buf.append('>');

        if (rendererMetaOptions.getRenderer() == null) {
            simpleProp.getOutput().render(value, buf);
        } else {
            EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
            context.setStringBuilderAndReset(buf);
            context.setPropertyName(simpleProp.getName());
            context.setPropertyValue(value);
            context.setDefaultRenderer(simpleProp.getOutput());
            rendererMetaOptions.getRenderer().render(context);
        }

        buf.append("</");
        buf.append(simpleProp.getName());
        buf.append('>');
        buf.append(NEWLINE);
    }

    GetterPair[] indexProps = meta.getIndexProperties();
    for (GetterPair indexProp : indexProps) {
        Object value = indexProp.getGetter().get(theEvent);

        if (value == null) {
            continue;
        }
        if (!value.getClass().isArray()) {
            log.warn("Property '" + indexProp.getName() + "' returned a non-array object");
            continue;
        }
        for (int i = 0; i < Array.getLength(value); i++) {
            Object arrayItem = Array.get(value, i);

            if (arrayItem == null) {
                continue;
            }

            ident(buf, level);
            buf.append('<');
            buf.append(indexProp.getName());
            buf.append('>');
            if (rendererMetaOptions.getRenderer() == null) {
                indexProp.getOutput().render(arrayItem, buf);
            } else {
                EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                context.setStringBuilderAndReset(buf);
                context.setPropertyName(indexProp.getName());
                context.setPropertyValue(arrayItem);
                context.setIndexedPropertyIndex(i);
                context.setDefaultRenderer(indexProp.getOutput());
                rendererMetaOptions.getRenderer().render(context);
            }
            buf.append("</");
            buf.append(indexProp.getName());
            buf.append('>');
            buf.append(NEWLINE);
        }
    }

    GetterPair[] mappedProps = meta.getMappedProperties();
    for (GetterPair mappedProp : mappedProps) {
        Object value = mappedProp.getGetter().get(theEvent);

        if ((value != null) && (!(value instanceof Map))) {
            log.warn("Property '" + mappedProp.getName() + "' expected to return Map and returned "
                    + value.getClass() + " instead");
            continue;
        }

        ident(buf, level);
        buf.append('<');
        buf.append(mappedProp.getName());
        buf.append('>');
        buf.append(NEWLINE);

        if (value != null) {
            Map<String, Object> map = (Map<String, Object>) value;
            if (!map.isEmpty()) {
                String localDelimiter = "";
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                for (; it.hasNext();) {
                    Map.Entry<String, Object> entry = it.next();
                    if (entry.getKey() == null) {
                        continue;
                    }

                    buf.append(localDelimiter);
                    ident(buf, level + 1);
                    buf.append('<');
                    buf.append(entry.getKey());
                    buf.append('>');

                    if (entry.getValue() != null) {
                        OutputValueRenderer outputValueRenderer = new OutputValueRendererXMLString();

                        if (rendererMetaOptions.getRenderer() == null) {
                            outputValueRenderer.render(entry.getValue(), buf);
                        } else {
                            EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                            context.setStringBuilderAndReset(buf);
                            context.setPropertyName(mappedProp.getName());
                            context.setPropertyValue(entry.getValue());
                            context.setMappedPropertyKey(entry.getKey());
                            context.setDefaultRenderer(outputValueRenderer);
                            rendererMetaOptions.getRenderer().render(context);
                        }
                    }

                    buf.append('<');
                    buf.append(entry.getKey());
                    buf.append('>');
                    localDelimiter = NEWLINE;
                }
            }
        }

        buf.append(NEWLINE);
        ident(buf, level);
        buf.append("</");
        buf.append(mappedProp.getName());
        buf.append('>');
        buf.append(NEWLINE);
    }

    NestedGetterPair[] nestedProps = meta.getNestedProperties();
    for (NestedGetterPair nestedProp : nestedProps) {
        Object value = nestedProp.getGetter().getFragment(theEvent);

        if (value == null) {
            continue;
        }

        if (!nestedProp.isArray()) {
            if (!(value instanceof EventBean)) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }
            renderElementFragment((EventBean) value, buf, level, nestedProp, rendererMetaOptions);
        } else {
            if (!(value instanceof EventBean[])) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean[] and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }

            EventBean[] nestedEventArray = (EventBean[]) value;
            for (int i = 0; i < nestedEventArray.length; i++) {
                EventBean arrayItem = nestedEventArray[i];
                if (arrayItem == null) {
                    continue;
                }
                renderElementFragment(arrayItem, buf, level, nestedProp, rendererMetaOptions);
            }
        }
    }
}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

private void writeObject(JsonGenerator jg, Object value) throws IOException {
    if (value == null) {
        jg.writeNull();//from   w  ww.ja  va2s.  com
    } else {
        Class<?> c = value.getClass();
        if (c.isArray()) {
            jg.writeStartArray();
            int len = Array.getLength(value);
            for (int j = 0; j < len; j++) {
                Object item = Array.get(value, j);
                writeObject(jg, item);
            }
            jg.writeEndArray();
        } else if (value instanceof Number) {
            Number n = (Number) value;
            jg.writeNumber(n.toString());
        } else if (value instanceof Boolean) {
            Boolean b = (Boolean) value;
            jg.writeBoolean(b);
        } else if (value instanceof CompositeData) {
            CompositeData cds = (CompositeData) value;
            CompositeType comp = cds.getCompositeType();
            Set<String> keys = comp.keySet();
            jg.writeStartObject();
            for (String key : keys) {
                writeAttribute(jg, key, cds.get(key));
            }
            jg.writeEndObject();
        } else if (value instanceof TabularData) {
            TabularData tds = (TabularData) value;
            jg.writeStartArray();
            for (Object entry : tds.values()) {
                writeObject(jg, entry);
            }
            jg.writeEndArray();
        } else if (value instanceof GaugeValue) {
            ((GaugeValue) value).serialize(jg);
        } else {
            jg.writeString(value.toString());
        }
    }
}