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:Main.java

/**
 * Returns the <code>index</code>-th value in <code>object</code>, throwing
 * <code>IndexOutOfBoundsException</code> if there is no such element or 
 * <code>IllegalArgumentException</code> if <code>object</code> is not an 
 * instance of one of the supported types.
 * <p>//from w ww .j  a  va2  s.  c om
 * The supported types, and associated semantics are:
 * <ul>
 * <li> Map -- the value returned is the <code>Map.Entry</code> in position 
 *      <code>index</code> in the map's <code>entrySet</code> iterator, 
 *      if there is such an entry.</li>
 * <li> List -- this method is equivalent to the list's get method.</li>
 * <li> Array -- the <code>index</code>-th array entry is returned, 
 *      if there is such an entry; otherwise an <code>IndexOutOfBoundsException</code>
 *      is thrown.</li>
 * <li> Collection -- the value returned is the <code>index</code>-th object 
 *      returned by the collection's default iterator, if there is such an element.</li>
 * <li> Iterator or Enumeration -- the value returned is the
 *      <code>index</code>-th object in the Iterator/Enumeration, if there
 *      is such an element.  The Iterator/Enumeration is advanced to 
 *      <code>index</code> (or to the end, if <code>index</code> exceeds the 
 *      number of entries) as a side effect of this method.</li>
 * </ul>
 *
 * @param object  the object to get a value from
 * @param index  the index to get
 * @return the object at the specified index
 * @throws IndexOutOfBoundsException if the index is invalid
 * @throws IllegalArgumentException if the object type is invalid
 */
public static Object get(Object object, int index) {
    if (index < 0) {
        throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
    }
    if (object instanceof Map) {
        Map map = (Map) object;
        Iterator iterator = map.entrySet().iterator();
        return get(iterator, index);
    } else if (object instanceof List) {
        return ((List) object).get(index);
    } else if (object instanceof Object[]) {
        return ((Object[]) object)[index];
    } else if (object instanceof Iterator) {
        Iterator it = (Iterator) object;
        while (it.hasNext()) {
            index--;
            if (index == -1) {
                return it.next();
            } else {
                it.next();
            }
        }
        throw new IndexOutOfBoundsException("Entry does not exist: " + index);
    } else if (object instanceof Collection) {
        Iterator iterator = ((Collection) object).iterator();
        return get(iterator, index);
    } else if (object instanceof Enumeration) {
        Enumeration it = (Enumeration) object;
        while (it.hasMoreElements()) {
            index--;
            if (index == -1) {
                return it.nextElement();
            } else {
                it.nextElement();
            }
        }
        throw new IndexOutOfBoundsException("Entry does not exist: " + index);
    } else if (object == null) {
        throw new IllegalArgumentException("Unsupported object type: null");
    } else {
        try {
            return Array.get(object, index);
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
        }
    }
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

private static void dumpObject(JSONArray jsonArray, Class type, Object array, int index)
        throws JSONSerializationException, JSONException {
    if (type.isPrimitive()) {
        jsonArray.put(String.valueOf(Array.get(array, index)));
    } else if (type == String.class) {
        String val = (String) Array.get(array, index);
        if (val != null) {
            jsonArray.put(val);
        }//from www . j  a  va  2  s.c  o  m
    } else if (JSONSerializable.class.isAssignableFrom(type)) {
        JSONSerializable o = (JSONSerializable) Array.get(array, index);
        JSONObject jobj = serializeJSONObject(o);
        jsonArray.put(jobj);
    } else if (type.isArray() && array != null) {
        Class compType = type.getComponentType();
        Object subArray = Array.get(array, index);
        int len = Array.getLength(subArray);
        JSONArray arr = new JSONArray();
        for (int k = 0; k < len; ++k) {
            dumpObject(arr, compType, subArray, k);
        }
        jsonArray.put(arr);
    }
}

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);
        }/*ww w .  j a v  a2 s  . c  o 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;
}

From source file:com.cisco.oss.foundation.monitoring.ServerInfo.java

@SuppressWarnings("unchecked")
private static Object getChild(Object obj, String attributeName, Object value, boolean isSet)
        throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    int substrstart = attributeName.indexOf('[');
    int substrend = attributeName.indexOf(']');

    if (substrstart == -1) {
        if (isSet) {
            String strFunc = "set" + attributeName;
            callSetMethod(obj, value, strFunc);
            return null;
        } else {/*from  w w  w. ja v a  2s .  c  o  m*/
            String getStr = "get";
            StringBuilder strBuild = new StringBuilder(attributeName);
            strBuild.insert(0, getStr);

            String getFuncStr = strBuild.toString();

            Method m = obj.getClass().getMethod(getFuncStr);
            Object result = m.invoke(obj);

            return result;
        }
    } else {
        String firststr = attributeName.substring(0, substrstart);
        String secondstr = attributeName.substring(substrstart + 1, substrend);
        Object parentObj = obj;
        Object requests = parentObj.getClass().getDeclaredMethod("get" + firststr, new Class[] {})
                .invoke(parentObj, new Object[] {});

        if (requests instanceof Map) {
            Object result = ((HashMap) requests).get(secondstr);
            return result;
        } else if (requests instanceof List) {
            if (isSet) {
                ((List) requests).set(Integer.parseInt(secondstr), value);
                return null;
            } else {
                Object request = ((List) requests).get(Integer.parseInt(secondstr));
                return request;
            }
        } else if (requests.getClass().isArray()) {
            if (isSet) {
                Object[] arr = (Object[]) requests;
                Array.set(arr, Integer.parseInt(secondstr), value);
                return null;
            } else {
                Object[] arr = (Object[]) requests;
                return Array.get(arr, Integer.parseInt(secondstr));
            }
        } else {
            return null;
        }
    }
}

From source file:com.manydesigns.elements.forms.TableForm.java

public void writeToObject(Object obj) {
    Class clazz = obj.getClass();
    if (clazz.isArray()) { // Tratta obj come un array
        // Scorre tutti gli elementi dell'array obj,
        // indipendentemente da quante righe ci sono nel table form.
        // Eventualmente lancia Eccezione.
        final int arrayLength = Array.getLength(obj);
        for (int i = 0; i < arrayLength; i++) {
            Object currentObj = Array.get(obj, i);
            rows[i].writeToObject(currentObj);
        }/* w w w  .j a  v a2 s .  c o m*/
    } else if (Collection.class.isAssignableFrom(clazz)) {
        // Tratta obj come collection
        Collection collection = (Collection) obj;

        int i = 0;
        for (Object currentObj : collection) {
            rows[i].writeToObject(currentObj);
            i++;
        }
    }
}

From source file:solidstack.reflect.Dumper.java

public void dumpTo(Object o, DumpWriter out) {
    try {//from w  ww  .  j  a  v  a 2 s.  c o m
        if (o == null) {
            out.append("<null>");
            return;
        }
        Class<?> cls = o.getClass();
        if (cls == String.class) {
            out.append("\"").append(((String) o).replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r")
                    .replace("\t", "\\t").replace("\"", "\\\"")).append("\"");
            return;
        }
        if (o instanceof CharSequence) {
            out.append("(").append(o.getClass().getName()).append(")");
            dumpTo(o.toString(), out);
            return;
        }
        if (cls == char[].class) {
            out.append("(char[])");
            dumpTo(String.valueOf((char[]) o), out);
            return;
        }
        if (cls == byte[].class) {
            out.append("byte[").append(Integer.toString(((byte[]) o).length)).append("]");
            return;
        }
        if (cls == Class.class) {
            out.append(((Class<?>) o).getCanonicalName()).append(".class");
            return;
        }
        if (cls == File.class) {
            out.append("File( \"").append(((File) o).getPath()).append("\" )");
            return;
        }
        if (cls == AtomicInteger.class) {
            out.append("AtomicInteger( ").append(Integer.toString(((AtomicInteger) o).get())).append(" )");
            return;
        }
        if (cls == AtomicLong.class) {
            out.append("AtomicLong( ").append(Long.toString(((AtomicLong) o).get())).append(" )");
            return;
        }
        if (o instanceof ClassLoader) {
            out.append(o.getClass().getCanonicalName());
            return;
        }

        if (cls == java.lang.Short.class || cls == java.lang.Long.class || cls == java.lang.Integer.class
                || cls == java.lang.Float.class || cls == java.lang.Byte.class
                || cls == java.lang.Character.class || cls == java.lang.Double.class
                || cls == java.lang.Boolean.class || cls == BigInteger.class || cls == BigDecimal.class) {
            out.append("(").append(cls.getSimpleName()).append(")").append(o.toString());
            return;
        }

        String className = cls.getCanonicalName();
        if (className == null)
            className = cls.getName();
        out.append(className);

        if (this.skip.contains(className) || o instanceof java.lang.Thread) {
            out.append(" (skipped)");
            return;
        }

        Integer id = this.visited.get(o);
        if (id == null) {
            id = ++this.id;
            this.visited.put(o, id);
            if (!this.hideIds)
                out.append(" <id=" + id + ">");
        } else {
            out.append(" <refid=" + id + ">");
            return;
        }

        if (cls.isArray()) {
            if (Array.getLength(o) == 0)
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                int rowCount = Array.getLength(o);
                for (int i = 0; i < rowCount; i++) {
                    out.comma();
                    dumpTo(Array.get(o, i), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Collection && !this.overriddenCollection.contains(className)) {
            Collection<?> list = (Collection<?>) o;
            if (list.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Object value : list) {
                    out.comma();
                    dumpTo(value, out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Properties && !this.overriddenCollection.contains(className)) // Properties is a Map, so it must come before the Map
        {
            Field def = cls.getDeclaredField("defaults");
            if (!def.isAccessible())
                def.setAccessible(true);
            Properties defaults = (Properties) def.get(o);
            Hashtable<?, ?> map = (Hashtable<?, ?>) o;
            out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                out.comma();
                dumpTo(entry.getKey(), out);
                out.append(": ");
                dumpTo(entry.getValue(), out);
            }
            if (defaults != null && !defaults.isEmpty()) {
                out.comma().append("defaults: ");
                dumpTo(defaults, out);
            }
            out.newlineOrSpace().unIndent().append("]");
        } else if (o instanceof Map && !this.overriddenCollection.contains(className)) {
            Map<?, ?> map = (Map<?, ?>) o;
            if (map.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    out.comma();
                    dumpTo(entry.getKey(), out);
                    out.append(": ");
                    dumpTo(entry.getValue(), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Method) {
            out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();

            Field field = cls.getDeclaredField("clazz");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("clazz").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("name");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("name").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("parameterTypes");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("parameterTypes").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("returnType");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("returnType").append(": ");
            dumpTo(field.get(o), out);

            out.newlineOrSpace().unIndent().append("}");
        } else {
            ArrayList<Field> fields = new ArrayList<Field>();
            while (cls != Object.class) {
                Field[] fs = cls.getDeclaredFields();
                for (Field field : fs)
                    fields.add(field);
                cls = cls.getSuperclass();
            }

            Collections.sort(fields, new Comparator<Field>() {
                public int compare(Field left, Field right) {
                    return left.getName().compareTo(right.getName());
                }
            });

            if (fields.isEmpty())
                out.append(" {}");
            else {
                out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();
                for (Field field : fields)
                    if ((field.getModifiers() & Modifier.STATIC) == 0)
                        if (!this.hideTransients || (field.getModifiers() & Modifier.TRANSIENT) == 0) {
                            out.comma().append(field.getName()).append(": ");

                            if (!field.isAccessible())
                                field.setAccessible(true);

                            if (field.getType().isPrimitive())
                                if (field.getType() == boolean.class) // TODO More?
                                    out.append(field.get(o).toString());
                                else
                                    out.append("(").append(field.getType().getName()).append(")")
                                            .append(field.get(o).toString());
                            else
                                dumpTo(field.get(o), out);
                        }
                out.newlineOrSpace().unIndent().append("}");
            }
        }
    } catch (IOException e) {
        throw new FatalIOException(e);
    } catch (Exception e) {
        dumpTo(e.toString(), out);
    }
}

From source file:org.jboss.capedwarf.common.env.AbstractEnvironment.java

/**
 * Make a JSON text of an Object value. If the object has an
 * value.toJSONString() method, then that method will be used to produce
 * the JSON text. The method is required to produce a strictly
 * conforming text. If the object does not contain a toJSONString
 * method (which is the most common case), then a text will be
 * produced by other means. If the value is an array or Collection,
 * then a JSONArray will be made from it and its toJSONString method
 * will be called. If the value is a MAP, then a JSONObject will be made
 * from it and its toJSONString method will be called. Otherwise, the
 * value's toString method will be called, and the result will be quoted.
 * <p/>//from   w  ww .ja  v  a  2  s  .c o  m
 * <p/>
 * Warning: This method assumes that the data structure is acyclical.
 *
 * @param value The value to be serialized.
 * @return a printable, displayable, transmittable
 *         representation of the object, beginning
 *         with <code>{</code>&nbsp;<small>(left brace)</small> and ending
 *         with <code>}</code>&nbsp;<small>(right brace)</small>.
 * @throws JSONException If the value is or contains an invalid number.
 */
static String valueToString(Object value) throws JSONException {
    if (value == null) {
        return "null";
    }
    if (value instanceof Number) {
        return JSONObject.numberToString((Number) value);
    }
    if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
        return value.toString();
    }
    if (value instanceof Map) {
        return new JSONObject((Map) value).toString();
    }
    if (value instanceof Collection) {
        return new JSONArray((Collection) value).toString();
    }
    if (value.getClass().isArray()) {
        Collection<Object> collection = new ArrayList<Object>();
        for (int i = 0; i < Array.getLength(value); i++)
            collection.add(Array.get(value, i));

        return new JSONArray(collection).toString();
    }
    return JSONObject.quote(value.toString());
}

From source file:com.liferay.portal.template.soy.internal.SoyTemplate.java

protected Object getSoyMapValue(Object value) {
    if (value == null) {
        return null;
    }//from   w  w w  . ja  v a 2s . c  o m

    Class<?> clazz = value.getClass();

    if (ClassUtils.isPrimitiveOrWrapper(clazz) || value instanceof String) {
        return value;
    }

    if (clazz.isArray()) {
        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < Array.getLength(value); i++) {
            Object object = Array.get(value, i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Iterable) {
        @SuppressWarnings("unchecked")
        Iterable<Object> iterable = (Iterable<Object>) value;

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

        for (Object object : iterable) {
            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) value;

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

        for (int i = 0; i < jsonArray.length(); i++) {
            Object object = jsonArray.opt(i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) value;

        Map<Object, Object> newMap = new TreeMap<>();

        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object newKey = getSoyMapValue(entry.getKey());

            if (newKey == null) {
                continue;
            }

            Object newValue = getSoyMapValue(entry.getValue());

            newMap.put(newKey, newValue);
        }

        return newMap;
    }

    if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;

        Map<String, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.get(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof org.json.JSONObject) {
        org.json.JSONObject jsonObject = (org.json.JSONObject) value;

        Map<Object, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.opt(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof SoyRawData) {
        SoyRawData soyRawData = (SoyRawData) value;

        return soyRawData.getValue();
    }

    Map<String, Object> newMap = new TreeMap<>();

    BeanPropertiesUtil.copyProperties(value, newMap);

    if (newMap.isEmpty()) {
        return null;
    }

    return getSoyMapValue(newMap);
}

From source file:com.github.mybatis.spring.MapperFactoryBean.java

private void evalArray(Object arr, StringBuilder sbd) {
    int sz = Array.getLength(arr);
    if (sz == 0) {
        sbd.append("[]");
        return;//from   w w w  .  ja  v  a2 s  .  c  o  m
    }
    Class<?> clz = Array.get(arr, 0).getClass();
    if (clz == Byte.class) {
        sbd.append("Byte[").append(sz).append(']');
        return;
    }
    if (isPrimitive(clz)) {
        sbd.append('[');
        int len = Math.min(sz, 10);
        for (int i = 0; i < len; i++) {
            Object obj = Array.get(arr, i);
            if (isPrimitive(obj.getClass())) {
                sbd.append(evalPrimitive(obj));
            } else {
                sbd.append(obj.getClass().getSimpleName()).append(":OBJ");
            }
            sbd.append(',');
        }
        if (sz > 10) {
            sbd.append(",...,len=").append(sz);
        }
        if (sbd.charAt(sbd.length() - 1) == ',') {
            sbd.setCharAt(sbd.length() - 1, ']');
        } else {
            sbd.append(']');
        }
    } else {
        sbd.append("[len=").append(sz).append(']');
    }
}

From source file:org.apache.hadoop.hive.metastore.VerifyingObjectStore.java

private static void dumpObject(StringBuilder errorStr, String name, Object p, Class<?> c, int level)
        throws IllegalAccessException {
    String offsetStr = repeat("  ", level);
    if (p == null || c == String.class || c.isPrimitive() || ClassUtils.wrapperToPrimitive(c) != null) {
        errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
    } else if (ClassUtils.isAssignable(c, Iterable.class)) {
        errorStr.append(offsetStr).append(name + " is an iterable\n");
        Iterator<?> i1 = ((Iterable<?>) p).iterator();
        int i = 0;
        while (i1.hasNext()) {
            Object o1 = i1.next();
            Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
            dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
        }//from w  ww. j  av a  2s.  c o  m
    } else if (c.isArray()) {
        int len = Array.getLength(p);
        Class<?> t = c.getComponentType();
        errorStr.append(offsetStr).append(name + " is an array\n");
        for (int i = 0; i < len; ++i) {
            dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
        }
    } else if (ClassUtils.isAssignable(c, Map.class)) {
        Map<?, ?> c1 = (Map<?, ?>) p;
        errorStr.append(offsetStr).append(name + " is a map\n");
        dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
        dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
    } else {
        errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
        // TODO: this doesn't include superclass.
        Field[] fields = c.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers()))
                continue;
            dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
        }
    }
}