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:edu.psu.chemxseer.structure.util.ArrayIterator.java

/**
 * Returns the next element in the array.
 * //from  www.  ja  v  a  2s  . c  o m
 * @return the next element in the array
 * @throws NoSuchElementException
 *             if all the elements in the array have already been returned
 */
@Override
public Object next() {
    if (hasNext() == false) {
        throw new NoSuchElementException();
    }
    return Array.get(array, index++);
}

From source file:org.openTwoFactor.clientExt.net.sf.ezmorph.array.CharacterObjectArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }//from  w ww.j  a va  2  s.com

    if (CHARACTER_OBJECT_ARRAY_CLASS.isAssignableFrom(array.getClass())) {
        // no conversion needed
        return (Character[]) array;
    }

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(Character.class, dimensions);
        if (dims == 1) {
            CharMorpher morpher = null;
            if (isUseDefault()) {
                if (defaultValue == null) {
                    for (int index = 0; index < length; index++) {
                        Array.set(result, index, null);
                    }
                    return result;
                } else {
                    morpher = new CharMorpher(defaultValue.charValue());
                }
            } else {
                morpher = new CharMorpher();
            }
            for (int index = 0; index < length; index++) {
                Array.set(result, index, new Character(morpher.morph(Array.get(array, index))));
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}

From source file:org.kordamp.ezmorph.bean.MorphDynaBean.java

public Object get(String name, int index) {
    DynaProperty dynaProperty = getDynaProperty(name);

    Class type = dynaProperty.getType();
    if (!type.isArray() && !List.class.isAssignableFrom(type)) {
        throw new MorphException("Non-Indexed property name: " + name + " index: " + index);
    }/* w  w w .j a va 2 s .c o m*/

    Object value = dynaValues.get(name);

    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.axis.encoding.ser.BeanPropertyTarget.java

/**
 * set the bean property with specified value
 * @param value is the value./*from  w  w w .  j a va2s .  com*/
 */
public void set(Object value) throws SAXException {

    try {
        // Set the value on the bean property. 
        // Use the indexed property method if the 
        // index is set.
        if (index < 0) {
            pd.set(object, value);
        } else {
            pd.set(object, index, value);
        }
    } catch (Exception e) {

        try {
            // If an exception occurred, 
            // see it the value can be converted into
            // the expected type.
            Class type = pd.getType();

            if (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive()
                    && type.isArray() && type.getComponentType().equals(Object.class)) {
                //we make our own array type here.
                type = Array.newInstance(JavaUtils.getWrapperClass(value.getClass().getComponentType()), 0)
                        .getClass();
            }

            if (JavaUtils.isConvertable(value, type)) {
                value = JavaUtils.convert(value, type);
                if (index < 0)
                    pd.set(object, value);
                else
                    pd.set(object, index, value);
            } else {
                // It is possible that an indexed
                // format was expected, but the
                // entire array was sent.  In such 
                // cases traverse the array and 
                // call the setter for each item.
                if (index == 0 && value.getClass().isArray() && !type.getClass().isArray()) {
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object item = JavaUtils.convert(Array.get(value, i), type);
                        pd.set(object, i, item);
                    }
                } else {
                    // Can't proceed.  Throw an exception that
                    // will be caught in the catch block below.
                    throw e;
                }
            }
        } catch (Exception ex) {
            // Throw a SAX exception with an informative
            // message.
            String field = pd.getName();
            if (index >= 0) {
                field += "[" + index + "]";
            }
            if (log.isErrorEnabled()) {
                //TODO: why is this just logged on the server-side and not thrown back to the client???
                String valueType = "null";
                if (value != null)
                    valueType = value.getClass().getName();
                log.error(Messages.getMessage("cantConvert02", new String[] { valueType, field,
                        (index >= 0) ? pd.getType().getComponentType().getName() : pd.getType().getName() }));
            }
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t != null) {
                    String classname = this.object.getClass().getName();
                    //show the context where this exception occured.
                    throw new SAXException(Messages.getMessage("cantConvert04", new String[] { classname, field,
                            (value == null) ? null : value.toString(), t.getMessage() }));
                }
            }
            throw new SAXException(ex);
        }
    }
}

From source file:org.apache.catalina.mbeans.MBeanDumper.java

/**
 * The following code to dump MBeans has been copied from JMXProxyServlet.
 *
 *//*from w  w  w .ja  va 2s . c o  m*/
public static String dumpBeans(MBeanServer mbeanServer, Set<ObjectName> names) {
    StringBuilder buf = new StringBuilder();
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        buf.append("Name: ");
        buf.append(oname.toString());
        buf.append(CRLF);

        try {
            MBeanInfo minfo = mbeanServer.getMBeanInfo(oname);
            // can't be null - I think
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mbeanServer.getAttribute(oname, "modelerType");
            }
            buf.append("modelerType: ");
            buf.append(code);
            buf.append(CRLF);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable())
                    continue;
                String attName = attrs[i].getName();
                if ("modelerType".equals(attName))
                    continue;
                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mbeanServer.getAttribute(oname, attName);
                } catch (JMRuntimeException rme) {
                    Throwable cause = rme.getCause();
                    if (cause instanceof UnsupportedOperationException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else if (cause instanceof NullPointerException) {
                        if (log.isDebugEnabled()) {
                            log.debug("Error getting attribute " + oname + " " + attName, rme);
                        }
                    } else {
                        log.error("Error getting attribute " + oname + " " + attName, rme);
                    }
                    continue;
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.error("Error getting attribute " + oname + " " + attName, t);
                    continue;
                }
                if (value == null)
                    continue;
                String valueString;
                try {
                    Class<?> c = value.getClass();
                    if (c.isArray()) {
                        int len = Array.getLength(value);
                        StringBuilder sb = new StringBuilder(
                                "Array[" + c.getComponentType().getName() + "] of length " + len);
                        if (len > 0) {
                            sb.append(CRLF);
                        }
                        for (int j = 0; j < len; j++) {
                            sb.append("\t");
                            Object item = Array.get(value, j);
                            if (item == null) {
                                sb.append("NULL VALUE");
                            } else {
                                try {
                                    sb.append(escape(item.toString()));
                                } catch (Throwable t) {
                                    ExceptionUtils.handleThrowable(t);
                                    sb.append("NON-STRINGABLE VALUE");
                                }
                            }
                            if (j < len - 1) {
                                sb.append(CRLF);
                            }
                        }
                        valueString = sb.toString();
                    } else {
                        valueString = escape(value.toString());
                    }
                    buf.append(attName);
                    buf.append(": ");
                    buf.append(valueString);
                    buf.append(CRLF);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                }
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
        buf.append(CRLF);
    }
    return buf.toString();

}

From source file:org.jolokia.converter.json.ArrayExtractor.java

/**
 * Set a value in an array//from   www. j a va2  s  .com
 *
 * @param pConverter the global converter in order to be able do dispatch for
 *        serializing inner data types
 * @param pInner object on which to set the value (which must be a {@link List})
 * @param pIndex index (as string) where to set the value within the array
 * @param pValue the new value to set
        
 * @return the old value at this index
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pIndex, Object pValue)
        throws IllegalAccessException, InvocationTargetException {
    Class clazz = pInner.getClass();
    if (!clazz.isArray()) {
        throw new IllegalArgumentException("Not an array to set a value, but " + clazz + ". (index = " + pIndex
                + ", value = " + pValue + ")");
    }
    int idx;
    try {
        idx = Integer.parseInt(pIndex);
    } catch (NumberFormatException exp) {
        throw new IllegalArgumentException("Non-numeric index for accessing array " + pInner + ". (index = "
                + pIndex + ", value to set = " + pValue + ")", exp);
    }
    Class type = clazz.getComponentType();
    Object value = pConverter.prepareValue(type.getName(), pValue);
    Object oldValue = Array.get(pInner, idx);
    Array.set(pInner, idx, value);
    return oldValue;
}

From source file:org.jboss.dashboard.ui.taglib.formatter.ForFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    log.debug("Servicing ForFormatter.");
    Object array = getParameter("array");
    if (array == null) {
        Object componentName = getParameter("factoryElement");
        Object propertyName = getParameter("property");
        if (componentName != null) {
            Object component = Factory.lookup((String) componentName);
            array = component;//from www .j  a v  a  2s.  c  o  m
            if (propertyName != null) {
                JXPathContext ctx = JXPathContext.newContext(component);
                try {
                    array = ctx.getValue((String) propertyName);
                } catch (Exception e) {
                    log.debug("Error:", e);
                }
            }
        }
    }
    String sortProperties = (String) getParameter("sortProperties");

    Iterator iterator = null;
    if (array == null) {
        renderFragment("empty");
        return;
    }

    if (array instanceof Collection) {
        iterator = ((Collection) array).iterator();
    } else if (array.getClass().isArray()) {
        final Object theArray = array;
        iterator = new Iterator() {
            int index = 0;

            public void remove() {
                throw new UnsupportedOperationException();
            }

            public boolean hasNext() {
                return Array.getLength(theArray) > index;
            }

            public Object next() {
                return Array.get(theArray, index++);
            }
        };
    } else if (array instanceof Iterator) {
        iterator = (Iterator) array;
    } else if (array instanceof Enumeration) {
        List l = new ArrayList();
        while (((Enumeration) array).hasMoreElements()) {
            l.add(((Enumeration) array).nextElement());
        }
        iterator = l.iterator();
    }

    if (sortProperties != null) {
        iterator = getSortedIterator(iterator, sortProperties);
    }

    if (iterator != null && iterator.hasNext()) {
        renderFragment("outputStart");
        int i = 0;
        while (iterator.hasNext()) {
            Object o = iterator.next();
            setAttribute("index", new Integer(i));
            setAttribute("count", new Integer(++i));
            if (o != null)
                setAttribute("element", o);
            else
                setAttribute("element", getParameter("nullValue"));
            renderFragment("output");
        }
        renderFragment("outputEnd");
    } else {
        renderFragment("empty");
    }
}

From source file:org.ldaptive.beans.spring.SpelAttributeValueMutator.java

/**
 * Uses the configured expression and evaluation context to retrieve values
 * from the supplied object. Values are the placed in a collection and
 * returned./* w  ww .  ja  v  a2s .  com*/
 *
 * @param  <T>  either String or byte[]
 * @param  object  to get values from
 * @param  type  of objects to place in the collection
 *
 * @return  values in the supplied object
 */
protected <T> Collection<T> getValues(final Object object, final Class<T> type) {
    Collection<T> values = null;
    final Object converted = expression.getValue(evaluationContext, object);
    if (converted != null) {
        if (converted instanceof byte[] || converted instanceof char[]) {
            values = createCollection(List.class, 1);

            final T value = convertValue(converted, converted.getClass(), type);
            if (value != null) {
                values.add(value);
            }
        } else if (converted.getClass().isArray()) {
            final int length = Array.getLength(converted);
            values = createCollection(List.class, length);
            for (int i = 0; i < length; i++) {
                final Object o = Array.get(converted, i);
                if (o != null) {
                    final T value = convertValue(o, o.getClass(), type);
                    if (value != null) {
                        values.add(value);
                    }
                }
            }
        } else if (Collection.class.isAssignableFrom(converted.getClass())) {
            final Collection<?> col = (Collection<?>) converted;
            values = createCollection(converted.getClass(), col.size());
            for (Object o : col) {
                if (o != null) {
                    final T value = convertValue(o, o.getClass(), type);
                    if (value != null) {
                        values.add(value);
                    }
                }
            }
        } else {
            values = createCollection(List.class, 1);

            final T value = convertValue(converted, converted.getClass(), type);
            if (value != null) {
                values.add(value);
            }
        }
    }
    return values;
}

From source file:ome.util.ModelMapper.java

/**
 * known immutables are return unchanged.
 * //from w  w  w .  ja  va2  s .co  m
 * @param current
 * @return a possibly uninitialized object which will be finalized as the
 *         object graph is walked.
 */
public Object findTarget(Object current) {

    // IMMUTABLES
    if (null == current || current instanceof Number || current instanceof String || current instanceof Boolean
            || current instanceof Timestamp || current instanceof Class) {
        return current;
    }

    Object target = model2target.get(current);
    if (null == target) {
        Class currentType = current.getClass();
        Class targetType = null;

        if (currentType.isArray()) {

            Class componentType = null;
            try {
                int length = Array.getLength(current);
                componentType = currentType.getComponentType();
                target = Array.newInstance(componentType, length);
                for (int i = 0; i < length; i++) {
                    Object currentValue = Array.get(current, i);
                    Object targetValue = this.filter("ARRAY", currentValue);
                    Array.set(target, i, targetValue);
                }
            } catch (Exception e) {
                log.error("Error creating new array of type " + componentType, e);
                throwOnNewInstanceException(current, componentType, e);
            }

        } else {
            targetType = findClass(currentType);

            if (null == targetType) {
                throw new InternalException("Cannot handle type:" + current);
            }

            try {
                target = targetType.newInstance();
            } catch (Exception e) {
                log.error("Error creating new instance of target type" + current, e);
                throwOnNewInstanceException(current, targetType, e);
            }

        }
        model2target.put(current, target);
    }
    return target;
}

From source file:org.jboss.dashboard.ui.formatters.ForFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    log.debug("Servicing ForFormatter.");
    Object array = getParameter("array");
    if (array == null) {
        Object componentName = getParameter("factoryElement");
        Object propertyName = getParameter("property");
        if (componentName != null) {
            Object component = CDIBeanLocator.getBeanByNameOrType((String) componentName);
            array = component;/*from  www.  ja  va2  s .c o m*/
            if (propertyName != null) {
                JXPathContext ctx = JXPathContext.newContext(component);
                try {
                    array = ctx.getValue((String) propertyName);
                } catch (Exception e) {
                    log.debug("Error:", e);
                }
            }
        }
    }
    String sortProperties = (String) getParameter("sortProperties");

    Iterator iterator = null;
    if (array == null) {
        renderFragment("empty");
        return;
    }

    if (array instanceof Collection) {
        iterator = ((Collection) array).iterator();
    } else if (array.getClass().isArray()) {
        final Object theArray = array;
        iterator = new Iterator() {
            int index = 0;

            public void remove() {
                throw new UnsupportedOperationException();
            }

            public boolean hasNext() {
                return Array.getLength(theArray) > index;
            }

            public Object next() {
                return Array.get(theArray, index++);
            }
        };
    } else if (array instanceof Iterator) {
        iterator = (Iterator) array;
    } else if (array instanceof Enumeration) {
        List l = new ArrayList();
        while (((Enumeration) array).hasMoreElements()) {
            l.add(((Enumeration) array).nextElement());
        }
        iterator = l.iterator();
    }

    if (sortProperties != null) {
        iterator = getSortedIterator(iterator, sortProperties);
    }

    if (iterator != null && iterator.hasNext()) {
        renderFragment("outputStart");
        int i = 0;
        while (iterator.hasNext()) {
            Object o = iterator.next();
            setAttribute("index", new Integer(i));
            setAttribute("count", new Integer(++i));
            if (o != null)
                setAttribute("element", o);
            else
                setAttribute("element", getParameter("nullValue"));
            renderFragment("output");
        }
        renderFragment("outputEnd");
    } else {
        renderFragment("empty");
    }
}