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:io.wcm.caconfig.editor.impl.ConfigDataServlet.java

private Object toJsonValue(Object value) {
    if (value == null) {
        return null;
    }//from w  w  w.j  a  va  2s  .co  m
    if (value.getClass().isArray()) {
        JSONArray array = new JSONArray();
        for (int i = 0; i < Array.getLength(value); i++) {
            array.put(Array.get(value, i));
        }
        return array;
    } else {
        return value;
    }
}

From source file:com.espertech.esper.event.util.XMLRendererImpl.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 a2s.co  m*/

        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 = OutputValueRendererFactory
                                .getOutputValueRenderer(entry.getValue().getClass(), rendererMetaOptions);
                        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:ObjectInspector.java

/**
 * Attempts to build a nicer looking string than the basic
 * {@link Object}.toString()//from  w w  w  . j  a  v a2  s.  co  m
 * 
 * @param o
 *           The object to build from
 * @return A descriptive string
 */
private static String buildString(Object o) {
    if (o == null) {
        return "null";
    }

    // first see if there is a version of toString more specific
    // than that supplied by Object...
    try {
        Method m = o.getClass().getMethod("toString");

        if (!m.getDeclaringClass().equals(Object.class)) {
            return o.toString();
        }
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    }

    // then see if it is an array...
    if (o.getClass().isArray()) {
        StringBuilder buff = new StringBuilder(" [ ");

        for (int i = 0; i < Array.getLength(o); i++) {
            /*
             * this could recurse infinitely, but only if the user is
             * trying to be malicious, like so - Object[] array = new
             * Object[ 1 ]; array[ 0 ] = array; - which, I'm sure
             * we'll agree, is and odd thing to do. I say let the
             * StackOverflowException catch it.
             */

            buff.append(buildString(Array.get(o, i)));
            buff.append(", ");
        }

        if (Array.getLength(o) > 0) {
            buff.delete(buff.length() - 2, buff.length());
        }

        buff.append(" ]");

        return buff.toString();
    }

    return getObjectPosition(o);
}

From source file:com.datos.vfs.util.DelegatingFileSystemOptionsBuilder.java

/**
 * invokes the method with the converted values
 *//* w  w w  .j a va 2 s. c o  m*/
private void invokeSetter(final Class<?> valueParameter, final Context ctx, final Method configSetter,
        final Object values) throws FileSystemException {
    Object[] args;
    if (valueParameter.isArray()) {
        args = new Object[] { ctx.fso, values };
    } else {
        args = new Object[] { ctx.fso, Array.get(values, 0) };
    }
    try {
        configSetter.invoke(ctx.fileSystemConfigBuilder, args);
    } catch (final IllegalAccessException e) {
        throw new FileSystemException(e);
    } catch (final InvocationTargetException e) {
        throw new FileSystemException(e);
    }
}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void writeObject(JsonGenerator jg, Object value) throws IOException {
    if (value == null) {
        jg.writeNull();//from ww  w.  j  a v  a  2  s. 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;
            if (value instanceof Double && (((Double) value).isInfinite() || ((Double) value).isNaN())) {
                jg.writeString(n.toString());
            } else {
                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());
        }
    }
}

From source file:com.sun.faces.el.PropertyResolverImpl.java

public boolean isReadOnly(Object base, int index) {
    boolean result = false;

    if (base == null) {
        throw new PropertyNotFoundException("Error setting index '" + index + "' in bean of type null");
    }/*from  w  ww.j a  v a  2s .  c o  m*/

    try {
        // Try to read the index, to trigger exceptions if any
        if (base.getClass().isArray()) {
            Array.get(base, index);
            result = false; // No way to know for sure
        } else if (base instanceof List) {
            ((List) base).get(index);
            result = false; // No way to know for sure
        } else {
            if (log.isDebugEnabled()) {
                log.debug("getValue:Property not found at index:" + index);
            }
            throw new EvaluationException(
                    "Bean of type " + base.getClass().getName() + " doesn't have indexed properties");
        }
    } catch (IndexOutOfBoundsException e) {
        throw new PropertyNotFoundException("Error setting index " + index, e);
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("setValue:Error setting index:" + index);
        }
        throw new EvaluationException("Error setting index " + index, t);
    }
    return result;
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Compares two JavaBeans for equality by comparing their properties and the
 * class of the beans./*from  w  w w .j  a  va2s. c om*/
 * 
 * @param bean1 Bean to compare
 * @param bean2 Bean to compare
 * @return True if {@code bean2} has the same properties with the same values
 *         as {@code bean1} and if they share the same class.
 */
public boolean equals(Object bean1, Object bean2) throws IntrospectionException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException {
    if ((null == bean1) && (null == bean2)) {
        return true;
    } else if ((null == bean1) || (null == bean2)) {
        return false;
    }
    if (bean1.getClass() != bean2.getClass()) {
        return false;
    }
    if (bean1.getClass().isArray() && bean2.getClass().isArray()) {
        if (Array.getLength(bean1) != Array.getLength(bean2)) {
            return false;
        }
        for (int i = 0; i < Array.getLength(bean1); i++) {
            if (!equals(Array.get(bean1, i), Array.get(bean2, i))) {
                return false;
            }
        }
        return true;
    } else if (bean1.getClass().isArray()) {
        return false;
    } else if (bean2.getClass().isArray()) {
        return false;
    } else if (isBean(bean1.getClass())) {
        BeanInfo bean1Info;
        try {
            bean1Info = Introspector.getBeanInfo(bean1.getClass(), Object.class);
        } catch (IntrospectionException e) {
            return false;
        }
        for (PropertyDescriptor p : bean1Info.getPropertyDescriptors()) {
            Method reader = p.getReadMethod();
            if (reader != null) {
                try {
                    Object value1 = reader.invoke(bean1);
                    Object value2 = reader.invoke(bean2);
                    if (!equals(value1, value2)) {
                        return false;
                    }
                } catch (IllegalArgumentException e) {
                    return false;
                } catch (IllegalAccessException e) {
                    return false;
                } catch (InvocationTargetException e) {
                    return false;
                }
            }
        }
        return true;
    } else {
        return bean1.equals(bean2);
    }
}

From source file:org.apache.hadoop.hbase.util.JSONBean.java

private static void writeObject(final JsonGenerator jg, final boolean description, Object value)
        throws IOException {
    if (value == null) {
        jg.writeNull();//from   w  ww . j a  v a 2s.co  m
    } 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, description, 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, null, cds.get(key));
            }
            jg.writeEndObject();
        } else if (value instanceof TabularData) {
            TabularData tds = (TabularData) value;
            jg.writeStartArray();
            for (Object entry : tds.values()) {
                writeObject(jg, description, entry);
            }
            jg.writeEndArray();
        } else {
            jg.writeString(value.toString());
        }
    }
}

From source file:org.apache.struts2.interceptor.debugging.DebuggingInterceptor.java

/**
 * Recursive function to serialize objects to XML. Currently it will
 * serialize Collections, maps, Arrays, and JavaBeans. It maintains a stack
 * of objects serialized already in the current functioncall. This is used
 * to avoid looping (stack overflow) of circular linked objects. Struts and
 * XWork objects are ignored./*  w  w  w.  j  a v a  2s  .  co m*/
 *
 * @param bean   The object you want serialized.
 * @param name   The name of the object, used for element &lt;name/&gt;
 * @param writer The XML writer
 * @param stack  List of objects we're serializing since the first calling
 *               of this function (to prevent looping on circular references).
 */
protected void serializeIt(Object bean, String name, PrettyPrintWriter writer, List<Object> stack) {
    writer.flush();
    // Check stack for this object
    if ((bean != null) && (stack.contains(bean))) {
        if (log.isInfoEnabled()) {
            log.info("Circular reference detected, not serializing object: " + name);
        }
        return;
    } else if (bean != null) {
        // Push object onto stack.
        // Don't push null objects ( handled below)
        stack.add(bean);
    }
    if (bean == null) {
        return;
    }
    String clsName = bean.getClass().getName();

    writer.startNode(name);

    // It depends on the object and it's value what todo next:
    if (bean instanceof Collection) {
        Collection col = (Collection) bean;

        // Iterate through components, and call ourselves to process
        // elements
        for (Object aCol : col) {
            serializeIt(aCol, "value", writer, stack);
        }
    } else if (bean instanceof Map) {

        Map map = (Map) bean;

        // Loop through keys and call ourselves
        for (Object key : map.keySet()) {
            Object Objvalue = map.get(key);
            serializeIt(Objvalue, key.toString(), writer, stack);
        }
    } else if (bean.getClass().isArray()) {
        // It's an array, loop through it and keep calling ourselves
        for (int i = 0; i < Array.getLength(bean); i++) {
            serializeIt(Array.get(bean, i), "arrayitem", writer, stack);
        }
    } else {
        if (clsName.startsWith("java.lang")) {
            writer.setValue(bean.toString());
        } else {
            // Not java.lang, so we can call ourselves with this object's
            // values
            try {
                BeanInfo info = Introspector.getBeanInfo(bean.getClass());
                PropertyDescriptor[] props = info.getPropertyDescriptors();

                for (PropertyDescriptor prop : props) {
                    String n = prop.getName();
                    Method m = prop.getReadMethod();

                    // Call ourselves with the result of the method
                    // invocation
                    if (m != null) {
                        serializeIt(m.invoke(bean), n, writer, stack);
                    }
                }
            } catch (Exception e) {
                log.error(e, e);
            }
        }
    }

    writer.endNode();

    // Remove object from stack
    stack.remove(bean);
}

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

/**
 * Handles conversion to an array of the specified type.
 * /*  w w  w .  j a v a2  s  .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;
}