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.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java

/**
 * {@inheritDoc}//from   ww w .  j  av a  2 s  .  c o  m
 */
@Override
public boolean canConvertValueForScript(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass) {
    boolean canConvert = expectedClass.isAssignableFrom(NativeArray.class);

    if (canConvert) {
        if (value instanceof Collection<?>) {
            final Collection<?> coll = (Collection<?>) value;
            for (final Object element : coll) {
                canConvert = canConvert && globalDelegate.canConvertValueForScript(element);

                if (!canConvert) {
                    break;
                }
            }
        } else if (value.getClass().isArray()) {
            final int length = Array.getLength(value);
            for (int idx = 0; idx < length && canConvert; idx++) {
                canConvert = canConvert && globalDelegate.canConvertValueForScript(Array.get(value, idx));
            }
        } else {
            canConvert = false;
        }
    }

    return canConvert;
}

From source file:com.frostwire.android.gui.StoragePicker.java

private static String getVolumePath(StorageManager mStorageManager, final String volumeId) {
    try {//from w w w.  j  a  v a2 s.c  om
        Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
        Method getUuid = storageVolumeClazz.getMethod("getUuid");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
        Object result = getVolumeList.invoke(mStorageManager);

        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String uuid = (String) getUuid.invoke(storageVolumeElement);
            Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);

            // primary volume?
            if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                return (String) getPath.invoke(storageVolumeElement);
            }

            // other volumes?
            if (uuid != null) {
                if (uuid.equals(volumeId)) {
                    return (String) getPath.invoke(storageVolumeElement);
                }
            }
        }

        // not found.
        return null;
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.espertech.esper.event.util.JSONRendererImpl.java

private static void recursiveRender(EventBean theEvent, StringBuilder buf, int level, RendererMeta meta,
        RendererMetaOptions rendererOptions) {
    String delimiter = "";

    // simple properties
    GetterPair[] simpleProps = meta.getSimpleProperties();
    if (rendererOptions.getRenderer() == null) {
        for (GetterPair simpleProp : simpleProps) {
            Object value = simpleProp.getGetter().get(theEvent);
            writeDelimitedIndentedProp(buf, delimiter, level, simpleProp.getName());
            simpleProp.getOutput().render(value, buf);
            delimiter = COMMA_DELIMITER_NEWLINE;
        }/*ww w  . ja v  a  2 s.  co  m*/
    } else {
        EventPropertyRendererContext context = rendererOptions.getRendererContext();
        context.setStringBuilderAndReset(buf);
        for (GetterPair simpleProp : simpleProps) {
            Object value = simpleProp.getGetter().get(theEvent);
            writeDelimitedIndentedProp(buf, delimiter, level, simpleProp.getName());
            context.setDefaultRenderer(simpleProp.getOutput());
            context.setPropertyName(simpleProp.getName());
            context.setPropertyValue(value);
            rendererOptions.getRenderer().render(context);
            delimiter = COMMA_DELIMITER_NEWLINE;
        }
    }

    GetterPair[] indexProps = meta.getIndexProperties();
    for (GetterPair indexProp : indexProps) {
        Object value = indexProp.getGetter().get(theEvent);
        writeDelimitedIndentedProp(buf, delimiter, level, indexProp.getName());

        if (value == null) {
            buf.append("null");
        } else {
            if (!value.getClass().isArray()) {
                buf.append("[]");
            } else {
                buf.append('[');
                String arrayDelimiter = "";

                if (rendererOptions.getRenderer() == null) {
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object arrayItem = Array.get(value, i);
                        buf.append(arrayDelimiter);
                        indexProp.getOutput().render(arrayItem, buf);
                        arrayDelimiter = ", ";
                    }
                } else {
                    EventPropertyRendererContext context = rendererOptions.getRendererContext();
                    context.setStringBuilderAndReset(buf);
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object arrayItem = Array.get(value, i);
                        buf.append(arrayDelimiter);
                        context.setPropertyName(indexProp.getName());
                        context.setPropertyValue(arrayItem);
                        context.setIndexedPropertyIndex(i);
                        context.setDefaultRenderer(indexProp.getOutput());
                        rendererOptions.getRenderer().render(context);
                        arrayDelimiter = ", ";
                    }
                }
                buf.append(']');
            }
        }
        delimiter = COMMA_DELIMITER_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;
        }

        writeDelimitedIndentedProp(buf, delimiter, level, mappedProp.getName());

        if (value == null) {
            buf.append("null");
            buf.append(NEWLINE);
        } else {
            Map<String, Object> map = (Map<String, Object>) value;
            if (map.isEmpty()) {
                buf.append("{}");
                buf.append(NEWLINE);
            } else {
                buf.append('{');
                buf.append(NEWLINE);

                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) {
                        buf.append("null");
                    } else {
                        OutputValueRenderer outRenderer = OutputValueRendererFactory
                                .getOutputValueRenderer(entry.getValue().getClass(), rendererOptions);
                        if (rendererOptions.getRenderer() == null) {
                            outRenderer.render(entry.getValue(), buf);
                        } else {
                            EventPropertyRendererContext context = rendererOptions.getRendererContext();
                            context.setStringBuilderAndReset(buf);
                            context.setPropertyName(mappedProp.getName());
                            context.setPropertyValue(entry.getValue());
                            context.setMappedPropertyKey(entry.getKey());
                            context.setDefaultRenderer(outRenderer);
                            rendererOptions.getRenderer().render(context);
                        }
                    }
                    localDelimiter = COMMA_DELIMITER_NEWLINE;
                }

                buf.append(NEWLINE);
                ident(buf, level);
                buf.append('}');
            }
        }

        delimiter = COMMA_DELIMITER_NEWLINE;
    }

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

        writeDelimitedIndentedProp(buf, delimiter, level, nestedProp.getName());

        if (value == null) {
            buf.append("null");
        } else 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;
            }
            EventBean nestedEventBean = (EventBean) value;
            buf.append('{');
            buf.append(NEWLINE);

            recursiveRender(nestedEventBean, buf, level + 1, nestedProp.getMetadata(), rendererOptions);

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

            StringBuilder arrayDelimiterBuf = new StringBuilder();
            arrayDelimiterBuf.append(',');
            arrayDelimiterBuf.append(NEWLINE);
            ident(arrayDelimiterBuf, level + 1);

            EventBean[] nestedEventArray = (EventBean[]) value;
            String arrayDelimiter = "";
            buf.append('[');

            for (int i = 0; i < nestedEventArray.length; i++) {
                EventBean arrayItem = nestedEventArray[i];
                buf.append(arrayDelimiter);
                arrayDelimiter = arrayDelimiterBuf.toString();

                buf.append('{');
                buf.append(NEWLINE);

                recursiveRender(arrayItem, buf, level + 2, nestedProp.getMetadata(), rendererOptions);

                ident(buf, level + 1);
                buf.append('}');
            }
            buf.append(']');
        }
        delimiter = COMMA_DELIMITER_NEWLINE;
    }

    buf.append(NEWLINE);
}

From source file:edu.sdsc.scigraph.neo4j.GraphUtil.java

static <T> Set<T> getPropertiesAsSet(Object value, Class<T> type) {
    Set<T> set = new HashSet<>();
    if (value.getClass().isArray()) {
        List<Object> objects = new ArrayList<>();
        for (int i = 0; i < Array.getLength(value); i++) {
            objects.add(Array.get(value, i));
        }//from   ww  w .  j a v a 2s. c  o  m
        for (Object o : objects) {
            set.add(type.cast(o));
        }
    } else {
        set.add(type.cast(value));
    }
    return set;
}

From source file:de.pribluda.android.jsonmarshaller.JSONMarshaller.java

/**
 * recursively marshall [multidimensional? - of course!!! ] array
 *
 * @param array/*w  ww .  j  a v  a2 s. c o  m*/
 * @return
 */
public static JSONArray marshallArray(Object array)
        throws InvocationTargetException, NoSuchMethodException, JSONException, IllegalAccessException {
    if (array != null && array.getClass().isArray()) {
        Class<?> componentType = array.getClass().getComponentType();
        JSONArray retval = new JSONArray();
        final int arrayLength = Array.getLength(array);
        // stirngs and primitives must be marshalled directly
        if (componentType.isPrimitive() || String.class.equals(componentType)) {

            for (int i = 0; i < arrayLength; i++) {
                retval.put(Array.get(array, i));
            }
        } else if (componentType.isArray()) {
            // that's cool, nested array recurse
            for (int i = 0; i < arrayLength; i++) {
                retval.put(marshallArray(Array.get(array, i)));
            }
        } else {
            // treat component as a bean   if it got default constructor
            try {
                if (componentType.getConstructor() != null) {
                    for (int i = 0; i < arrayLength; i++) {
                        retval.put(marshall(Array.get(array, i)));
                    }
                }
            } catch (NoSuchMethodException ex) {
                // just ignore it here, it means no such constructor was found
            }
        }

        return retval;
    }

    return null;
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Try to clone the given object./*from  w w w. ja  v a2  s . c  o  m*/
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        Class<?> clazz = object.getClass();
        Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:net.sf.json.JSONDynaBean.java

/**
 * DOCUMENT ME!//w  w w  .ja  v a  2 s.co  m
 *
 * @param name DOCUMENT ME!
 * @param index DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public Object get(String name, int index) {
    Object value = dynaValues.get(name);

    if (value == null) {
        throw new NullPointerException("Unindexed property name: " + name + " index: " + index);
    } else if (!(value instanceof List) || !(value.getClass().isArray())) {
        throw new IllegalArgumentException("Non-Indexed property name: " + name + " index: " + index);
    }

    if (value.getClass().isArray()) {
        value = Array.get(value, index);
    } else if (value instanceof List) {
        value = ((List) value).get(index);
    }

    return value;
}

From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java

int setArrayField(List<OneField> record, int dataType, Field reflectedField) throws IllegalAccessException {
    Object array = reflectedField.get(userObject);
    int length = Array.getLength(array);
    for (int j = 0; j < length; j++) {
        record.add(new OneField(dataType, Array.get(array, j)));
    }/*w w  w. jav a2  s .c  o m*/
    return length;
}

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

private String renderAttElements(EventBean theEvent, int level, RendererMeta meta) {
    StringBuilder buf = new StringBuilder();

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

        if (value == null) {
            continue;
        }/* w  w  w  .j  a v a 2  s . co m*/
        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());

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

                    buf.append(" ");
                    buf.append(entry.getKey());
                    buf.append("=\"");
                    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("/>");
        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;
            }
            EventBean nestedEventBean = (EventBean) value;
            renderAttInner(buf, level, nestedEventBean, nestedProp);
        } 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];
                renderAttInner(buf, level, arrayItem, nestedProp);
            }
        }
    }

    return buf.toString();
}

From source file:jp.terasoluna.fw.web.struts.form.DynaValidatorActionFormEx.java

/**
 * CfbNXtv?peB?B/* w  ww . ja va  2s.  com*/
 *
 * <p>
 *  CfbNXOnull
 *  StrutsftHgg?B
 * </p>
 *
 * @param name tB?[h
 * @param index CfbNX
 * @return v?peBl
 */
@Override
public Object get(String name, int index) {
    if (log.isDebugEnabled()) {
        log.debug("get(" + name + ", " + index + ") called.");
    }

    Object value = dynaValues.get(name);
    if (value == null) {
        throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
    } else if (value.getClass().isArray()) {
        try {
            return (Array.get(value, index));
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    } else if (value instanceof List) {
        try {
            return ((List) value).get(index);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }
}