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

/**
 * General purpose list converter method. Will convert arrays, collections,
 * iterables etc. into lists./*from w  w  w .j av a  2s.  c o  m*/
 * 
 * If the argument is a single object (such as a String or a POJO) it will
 * be wrapped in a single-element list.
 * 
 * Null will be converted to the empty list.
 * 
 * @param obj
 *            any object
 * @return a list representation of the object
 */
public static List<?> toList(Object obj) {
    final List<Object> result;
    if (obj == null) {
        result = Collections.emptyList();
    } else if (obj instanceof List) {
        @SuppressWarnings("unchecked")
        List<Object> list = (List<Object>) obj;
        result = list;
    } else if (obj.getClass().isArray()) {
        int length = Array.getLength(obj);
        result = new ArrayList<Object>(length);
        for (int i = 0; i < length; i++) {
            result.add(Array.get(obj, i));
        }
    } else if (obj instanceof Iterable) {
        result = new ArrayList<Object>();
        for (Object item : (Iterable<?>) obj) {
            result.add(item);
        }
    } else if (obj instanceof Iterator) {
        result = new ArrayList<Object>();
        Iterator<?> it = (Iterator<?>) obj;
        while (it.hasNext()) {
            result.add(it.next());
        }
    } else {
        result = new ArrayList<Object>(1);
        result.add(obj);
    }
    return result;
}

From source file:Main.java

/**
 * <p>//from   w  w  w  .  j  a v a2 s  . co m
 * Converts an Object reference that is known to be an array into a List.
 * Semantically very similar to {@link java.util.Arrays#asList(Object[])}
 * except that this method can deal with arrays of primitives in the same
 * manner as arrays as objects.
 * </p>
 * 
 * <p>
 * A new List is created of the same size as the array, and elements are
 * copied from the array into the List. If elements are primitives then they
 * are converted to the appropriate wrapper types in order to return a List.
 * </p>
 * 
 * @param in
 *            an array of Objects or primitives (null values are not
 *            allowed)
 * @return a List containing an element for each element in the input array
 * @throws IllegalArgumentException
 *             thrown if the in parameter is null or not an array
 */
public static List<Object> asList(Object in) {
    if (in == null || !in.getClass().isArray()) {
        throw new IllegalArgumentException("Parameter to asObjectArray must be a non-null array.");
    } else {
        int length = Array.getLength(in);
        LinkedList<Object> list = new LinkedList<Object>();
        for (int i = 0; i < length; ++i) {
            list.add(i, Array.get(in, i));
        }

        return list;
    }
}

From source file:Main.java

/**
 * @return an Object array for the given object.
 *
 * @param obj  Object to convert to an array.  Converts primitive
 *             arrays to Object arrays consisting of their wrapper
 *             classes.  If the object is not an array (object or primitve)
 *             then a new array of the given type is created and the
 *             object is set as the sole element.
 *//*from  w  ww. ja  v  a  2 s  . c  o m*/
public static Object[] toArray(final Object obj) {
    // if the object is an array, the cast and return it.
    if (obj instanceof Object[]) {
        return (Object[]) obj;
    }

    // if the object is an array of primitives then wrap the array
    Class type = obj.getClass();
    Object array;
    if (type.isArray()) {
        int length = Array.getLength(obj);
        Class componentType = type.getComponentType();
        array = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(array, i, Array.get(obj, i));
        }
    } else {
        array = Array.newInstance(type, 1);
        Array.set(array, 0, obj);
    }

    return (Object[]) array;
}

From source file:ArrayConverter.java

private static void addToList(final List list, final Object array) {
    final int length = Array.getLength(array);
    for (int i = 0; i < length; i++) {
        final Object value = Array.get(array, i);
        if (value == null) {
            list.add(null);/*from  w w w  . j  av a2s .co m*/
            continue;
        }

        if (value.getClass().isArray() == false) {
            list.add(value);
            continue;
        }

        ArrayConverter.addToList(list, value);
    }
}

From source file:org.ajax4jsf.javascript.ScriptUtils.java

/**
 * Convert any Java Object to JavaScript representation ( as possible ).
 * @param obj// w w w. j  a  v  a  2 s  .c om
 * @return
 */
public static String toScript(Object obj) {
    if (null == obj) {
        return "null";
    } else if (obj instanceof ScriptString) {
        return ((ScriptString) obj).toScript();
    } else if (obj.getClass().isArray()) {
        StringBuilder ret = new StringBuilder("[");
        boolean first = true;
        for (int i = 0; i < Array.getLength(obj); i++) {
            Object element = Array.get(obj, i);
            if (!first) {
                ret.append(',');
            }
            ret.append(toScript(element));
            first = false;
        }
        return ret.append("] ").toString();
    } else if (obj instanceof Collection) {
        // Collections put as JavaScript array.

        @SuppressWarnings("unchecked")
        Collection<Object> collection = (Collection<Object>) obj;

        StringBuilder ret = new StringBuilder("[");
        boolean first = true;
        for (Iterator<Object> iter = collection.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (!first) {
                ret.append(',');
            }
            ret.append(toScript(element));
            first = false;
        }
        return ret.append("] ").toString();
    } else if (obj instanceof Map) {

        // Maps put as JavaScript hash.
        @SuppressWarnings("unchecked")
        Map<Object, Object> map = (Map<Object, Object>) obj;

        StringBuilder ret = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            if (!first) {
                ret.append(',');
            }

            addEncodedString(ret, entry.getKey());
            ret.append(":");
            ret.append(toScript(entry.getValue()));
            first = false;
        }
        return ret.append("} ").toString();
    } else if (obj instanceof Number || obj instanceof Boolean) {
        // numbers and boolean put as-is, without conversion
        return obj.toString();
    } else if (obj instanceof String) {
        // all other put as encoded strings.
        StringBuilder ret = new StringBuilder();
        addEncodedString(ret, obj);
        return ret.toString();
    } else if (obj instanceof Enum) {
        // all other put as encoded strings.
        StringBuilder ret = new StringBuilder();
        addEncodedString(ret, obj);
        return ret.toString();
    } else if (obj.getClass().getName().startsWith("java.sql.")) {
        StringBuilder ret = new StringBuilder("{");
        boolean first = true;
        for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(obj)) {
            String key = propertyDescriptor.getName();
            if ("class".equals(key)) {
                continue;
            }
            Object value = null;
            try {
                value = PropertyUtils.getProperty(obj, key);
            } catch (Exception e) {
                continue;
            }

            if (!first) {
                ret.append(',');
            }

            addEncodedString(ret, key);
            ret.append(":");
            ret.append(toScript(value));

            first = false;
        }
        return ret.append("} ").toString();
    }

    // All other objects threaded as Java Beans.
    try {
        StringBuilder ret = new StringBuilder("{");
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);
        boolean first = true;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String key = propertyDescriptor.getName();
            if ("class".equals(key)) {
                continue;
            }
            if (!first) {
                ret.append(',');
            }
            addEncodedString(ret, key);
            ret.append(":");
            ret.append(toScript(PropertyUtils.getProperty(obj, key)));
            first = false;
        }
        return ret.append("} ").toString();
    } catch (Exception e) {
        throw new FacesException("Error in conversion Java Object to JavaScript", e);
    }
}

From source file:ArrayListWrapper.java

public Object get(int index) {
    return Array.get(array, index);
}

From source file:Main.java

public static JSONArray toJsonArray(Array array) {
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < Array.getLength(array); i++) {
        Object elm = Array.get(array, i);
        if (elm instanceof Bundle) {
            jsonArray.put(toJsonObject((Bundle) elm));
        } else if (elm instanceof List<?>) {
            jsonArray.put(toJsonArray((List<?>) elm));
        } else if (elm instanceof Array) {
            jsonArray.put(toJsonArray((Array) elm));
        } else {//w w w .java2  s  .c  o  m
            jsonArray.put(elm.toString());
        }
    }
    return jsonArray;
}

From source file:Main.java

/**
 * Builds a bracketed CSV list from the array
 * @param array an array of Objects/*from ww  w  .j  a  va2  s.c o m*/
 * @return string
 */
public static String arrayToString(Object array) {

    int len = Array.getLength(array);
    int last = len - 1;
    StringBuffer sb = new StringBuffer(2 * (len + 1));

    sb.append('{');

    for (int i = 0; i < len; i++) {
        sb.append(Array.get(array, i));

        if (i != last) {
            sb.append(',');
        }
    }

    sb.append('}');

    return sb.toString();
}

From source file:com.opensymphony.webwork.util.ContainUtil.java

/**
       * Determine if <code>obj2</code> exists in <code>obj1</code>.
       */*from w w  w .java  2  s.  c o  m*/
       * <table borer="1">
       *  <tr>
       *      <td>Type Of obj1</td>
       *      <td>Comparison type</td>
       *  </tr>
       *  <tr>
       *      <td>null<td>
       *      <td>always return false</td>
       *  </tr>
       *  <tr>
       *      <td>Map</td>
       *      <td>Map containsKey(obj2)</td>
       *  </tr>
       *  <tr>
       *      <td>Collection</td>
       *      <td>Collection contains(obj2)</td>
       *  </tr>
       *  <tr>
       *      <td>Array</td>
       *      <td>there's an array element (e) where e.equals(obj2)</td>
       *  </tr>
       *  <tr>
       *      <td>Object</td>
       *      <td>obj1.equals(obj2)</td>
       *  </tr>
       * </table>
       *
       *
       * @param obj1
       * @param obj2
       * @return
       */
    public static boolean contains(Object obj1, Object obj2) {
        if ((obj1 == null) || (obj2 == null)) {
            //log.debug("obj1 or obj2 are null.");
            return false;
        }

        if (obj1 instanceof Map) {
            if (((Map) obj1).containsKey(obj2)) {
                //log.debug("obj1 is a map and contains obj2");
                return true;
            }
        } else if (obj1 instanceof Collection) {
            if (((Collection) obj1).contains(obj2)) {
                //log.debug("obj1 is a collection and contains obj2");
                return true;
            }
        } else if (obj1.getClass().isArray()) {
            for (int i = 0; i < Array.getLength(obj1); i++) {
                Object value = null;
                value = Array.get(obj1, i);

                if (value.equals(obj2)) {
                    //log.debug("obj1 is an array and contains obj2");
                    return true;
                }
            }
        } else if (obj1.equals(obj2)) {
            //log.debug("obj1 is an object and equals obj2");
            return true;
        }

        //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
        return false;
    }

From source file:com.chadekin.jadys.commons.formatters.ArrayValueFormatter.java

@Override
public String format(Object value) {
    String result = StringUtils.EMPTY;
    if (value != null) {
        List convertedValue = Lists.newArrayList();
        for (int index = 0; index < Array.getLength(value); index++) {
            convertedValue.add(Array.get(value, index));
        }/*from  ww  w  .ja  v  a2 s  . c om*/
        result = super.format(convertedValue);
    }
    return result;
}