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.sdsc.scigraph.services.jersey.writers.BbopJsGraphWriter.java

static Optional<String> getLabel(Vertex vertex) {
    Optional<String> label = Optional.absent();
    if (vertex.getPropertyKeys().contains(NodeProperties.LABEL)) {
        Object value = vertex.getProperty(NodeProperties.LABEL);
        if (value.getClass().isArray()) {
            label = Optional.of((String) Array.get(value, 0));
        } else if (value instanceof Iterable) {
            label = Optional.of((String) Iterables.getFirst((Iterable<?>) value, null));
        } else {// www.  j a v  a 2 s.  c om
            label = Optional.of((String) value);
        }
    }
    return label;
}

From source file:Main.java

public static JSONArray object2Json(Object data) throws JSONException {
    if (!data.getClass().isArray()) {
        throw new JSONException("Not a primitive data: " + data.getClass());
    }/*from  w  w w.j a  v  a 2 s . c  om*/
    final int length = Array.getLength(data);
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < length; ++i) {
        jsonArray.put(wrap(Array.get(data, i)));
    }

    return jsonArray;
}

From source file:mil.jpeojtrs.sca.util.PrimitiveArrayUtils.java

public static long[] convertToLongArray(final Object array) {
    if (array == null) {
        return null;
    }/*from w  ww .  j av  a  2  s.c  o m*/
    if (array instanceof long[]) {
        return (long[]) array;
    }
    if (array instanceof Long[]) {
        return ArrayUtils.toPrimitive((Long[]) array);
    }
    final long[] newArray = new long[Array.getLength(array)];
    for (int i = 0; i < newArray.length; i++) {
        final Number val = (Number) Array.get(array, i);
        newArray[i] = val.longValue();
    }
    return newArray;
}

From source file:de.ncoder.sensorsystem.android.logging.JSONUtils.java

public static Object wrap(Object o) {
    if (o == null) {
        return JSONObject.NULL;
    } else if (o instanceof JSONArray || o instanceof JSONObject) {
        return o;
    } else if (o.equals(JSONObject.NULL)) {
        return o;
    } else if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double
            || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short) {
        return o;
    } else if (o instanceof CharSequence) {
        return JSONObject.quote(o.toString());
    } else if (o instanceof Collection) {
        return new JSONArray((Collection) o);
    } else if (o.getClass().isArray()) {
        final int length = Array.getLength(o);
        List<Object> values = new ArrayList<>(length);
        for (int i = 0; i < length; ++i) {
            values.add(wrap(Array.get(o, i)));
        }/*from  w ww . j  av a 2 s .c  om*/
        return new JSONArray(values);
    } else if (o instanceof Map) {
        return new JSONObject((Map) o);
    } else if (o instanceof Location) {
        return wrapLocation((Location) o);
    } else if (o instanceof Bundle) {
        return wrapBundle((Bundle) o);
    }
    return o.toString();
}

From source file:com.base.dao.sql.ReflectionUtils.java

public static Object convertValue(Object value, Class toType) {
    Object result = null;/*from w w w  . j  av a 2 s  . co m*/
    if (value != null) {
        if (value.getClass().isArray() && toType.isArray()) {
            Class componentType = toType.getComponentType();
            result = Array.newInstance(componentType, Array.getLength(value));
            for (int i = 0, icount = Array.getLength(value); i < icount; i++) {
                Array.set(result, i, convertValue(Array.get(value, i), componentType));
            }
        } else {
            if ((toType == Integer.class) || (toType == Integer.TYPE))
                result = Integer.valueOf((int) longValue(value));
            if ((toType == Double.class) || (toType == Double.TYPE))
                result = new Double(doubleValue(value));
            if ((toType == Boolean.class) || (toType == Boolean.TYPE))
                result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE;
            if ((toType == Byte.class) || (toType == Byte.TYPE))
                result = Byte.valueOf((byte) longValue(value));
            if ((toType == Character.class) || (toType == Character.TYPE))
                result = new Character((char) longValue(value));
            if ((toType == Short.class) || (toType == Short.TYPE))
                result = Short.valueOf((short) longValue(value));
            if ((toType == Long.class) || (toType == Long.TYPE))
                result = Long.valueOf(longValue(value));
            if ((toType == Float.class) || (toType == Float.TYPE))
                result = new Float(doubleValue(value));
            if (toType == BigInteger.class)
                result = bigIntValue(value);
            if (toType == BigDecimal.class)
                result = bigDecValue(value);
            if (toType == String.class)
                result = stringValue(value);
            if (toType == Date.class) {
                result = DateUtils.toDate(stringValue(value));
            }
            if (Enum.class.isAssignableFrom(toType))
                result = enumValue((Class<Enum>) toType, value);
        }
    } else {
        if (toType.isPrimitive()) {
            result = primitiveDefaults.get(toType);
        }
    }
    return result;
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();/*from w ww  . ja v a  2 s  .  c om*/
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:org.apache.commons.functor.example.map.FixedSizeMap.java

public FixedSizeMap(Map<K, V> map) {
    super(map);// w  w  w.  ja  va2s .  c  om
    setOnPut(new BinaryFunction<Map<K, V>, Object[], V>() {
        public V evaluate(Map<K, V> map, Object[] b) {
            K key = (K) Array.get(b, 0);
            V value = (V) Array.get(b, 1);
            if (map.containsKey(key)) {
                return map.put(key, value);
            } else {
                throw new IllegalArgumentException();
            }
        }
    });

    setOnPutAll(new BinaryProcedure<Map<K, V>, Map<K, V>>() {
        public void run(Map<K, V> a, Map<K, V> b) {
            Map<K, V> dest = a;
            Map<K, V> src = b;

            if (GeneratorContains.instance().test(IteratorToGeneratorAdapter.adapt(src.keySet().iterator()),
                    Not.not(new ContainsKey(dest)))) {
                throw new IllegalArgumentException();
            } else {
                dest.putAll(src);
            }
        }
    });

    setOnRemove(new BinaryProcedureBinaryFunction<Map<K, V>, K, V>(
            (BinaryProcedure<? super Map<K, V>, ? super K>) new Throw<K, V>(
                    new UnsupportedOperationException())));
    setOnClear(new Throw<K, V>(new UnsupportedOperationException()));
}

From source file:Main.java

/**
 * Determine if <code>obj2</code> exists in <code>obj1</code>.
 *
 * <table borer="1">/*  w  w w  .j  a v  a 2s.  co m*/
 *  <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;
        }
    }
    if (obj1 instanceof Iterable) {
        Iterator iter = ((Iterable) obj1).iterator();
        while (iter.hasNext()) {
            Object value = iter.next();
            if (obj2.equals(value) || obj2.toString().equals(value)) {
                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 (obj2.equals(value)) {
                //log.debug("obj1 is an array and contains obj2");
                return true;
            }
        }
    } else if (obj1.toString().equals(obj2.toString())) {
        //log.debug("obj1 is an object and it's String representation equals obj2's String representation.");
        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:org.apache.commons.functor.example.map.PredicatedMap.java

public PredicatedMap(Map<K, V> map, final Predicate<K> keyPredicate, final Predicate<V> valuePredicate) {
    super(map);//from w  w  w. j a  v a2s.c o  m
    setOnPut(new ConditionalBinaryFunction<Map<K, V>, Object[], V>(new BinaryPredicate<Map<K, V>, Object[]>() {
        @SuppressWarnings("unchecked")
        public boolean test(Map<K, V> a, Object[] b) {
            return keyPredicate.test((K) Array.get(b, 0)) && valuePredicate.test((V) Array.get(b, 1));
        }
    }, DEFAULT_ON_PUT, BinaryProcedureBinaryFunction
            .<Map<K, V>, Object[], V>adapt(new Throw<Map<K, V>, Object>(new IllegalArgumentException()))));

    setOnPutAll(new BinaryProcedure<Map<K, V>, Map<K, V>>() {
        public void run(Map<K, V> dest, Map<K, V> src) {
            for (Iterator<Map.Entry<K, V>> iter = src.entrySet().iterator(); iter.hasNext();) {
                Map.Entry<K, V> pair = iter.next();
                if (keyPredicate.test(pair.getKey()) && valuePredicate.test(pair.getValue())) {
                    dest.put(pair.getKey(), pair.getValue());
                }
            }
        }
    });
}

From source file:org.cocoa4android.util.sbjson.SBJsonWriter.java

/**
 *  //from w  ww .  j a  v  a2 s . c o m
 * @param js   json
 * @param array   
 */
private static void serializeArray(JSONStringer js, Object array) {
    try {
        js.array();
        for (int i = 0; i < Array.getLength(array); ++i) {
            Object o = Array.get(array, i);
            serialize(js, o);
        }
        js.endArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
}