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:com.discovery.darchrow.lang.ArrayUtil.java

/**
 * ?./*from  w ww .  j  a v a2  s.c  o  m*/
 * (Returns the value of the indexed component in the specified array object.
 * The value is automatically wrapped in an object if it has a primitive type.)
 *
 * @param <T>
 *            the generic type
 * @param array
 *            
 * @param index
 *            
 * @return ,the (possibly wrapped) value of the indexed component in the specified array
 * @throws ArrayIndexOutOfBoundsException
 *             If the specified {@code index} argument is negative, or if it is greater than or equal to the length of the specified
 *             array
 * @see java.lang.reflect.Array#get(Object, int)
 */
@SuppressWarnings("unchecked")
public static <T> T getElement(Object array, int index) throws ArrayIndexOutOfBoundsException {
    return (T) Array.get(array, index);
}

From source file:com.carmanconsulting.cassidy.pojo.assembly.disassembler.ArrayDisassembler.java

@Override
public void disassemble(Object object, List<AssemblyStep> steps, CassidyContext context,
        DisassemblerService service) {//  ww  w  .  j a  v  a  2 s  . c om
    steps.add(new MarkStep());
    final int length = ArrayUtils.getLength(object);
    for (int i = 0; i < length; ++i) {
        final Object element = Array.get(object, i);
        steps.addAll(service.disassemble(element));
    }
    steps.add(new ArrayStep(object.getClass().getComponentType()));
}

From source file:edu.sdsc.scigraph.neo4j.GraphUtil.java

static Object getNewPropertyValue(Object originalValue, Object newValue) {
    Class<?> clazz = checkNotNull(newValue).getClass();
    boolean reduceToString = false;
    if (null != originalValue && originalValue.getClass().isArray()) {
        Class<?> originalClazz = Array.get(originalValue, 0).getClass();
        if (!originalClazz.equals(clazz)) {
            reduceToString = true;//from   w  w  w. j  av a  2  s  . co  m
            clazz = String.class;
        }
        newValue = reduceToString ? newValue.toString() : newValue;
        Object newArray = Array.newInstance(clazz, Array.getLength(originalValue) + 1);
        for (int i = 0; i < Array.getLength(originalValue); i++) {
            Object val = Array.get(originalValue, i);
            if (newValue.equals(val)) {
                return originalValue;
            }
            Array.set(newArray, i, reduceToString ? val.toString() : val);
        }
        Array.set(newArray, Array.getLength(originalValue), newValue);
        return newArray;
    } else if (null != originalValue) {
        if (!clazz.equals(originalValue.getClass())) {
            reduceToString = true;
            clazz = String.class;
        }
        originalValue = reduceToString ? originalValue.toString() : originalValue;
        newValue = reduceToString ? newValue.toString() : newValue;
        if (!originalValue.equals(newValue)) {
            Object newArray = Array.newInstance(clazz, 2);
            Array.set(newArray, 0, originalValue);
            Array.set(newArray, 1, newValue);
            return newArray;
        } else {
            return originalValue;
        }
    } else {
        return newValue;
    }
}

From source file:org.eclipse.scanning.scisoftpy.python.PythonUtils.java

/**
 * Convert tuples/lists of tuples/lists to Java lists of lists. Also convert complex numbers to Apache Commons
 * version and Jython strings to strings
 * /*from  w  w w  .  ja v a2  s.com*/
 * @param obj
 * @return converted object
 */
public static Object convertToJava(Object obj) {
    if (obj == null || obj instanceof PyNone)
        return null;

    if (obj instanceof PySequenceList) {
        obj = ((PySequenceList) obj).toArray();
    }

    if (obj instanceof PyArray) {
        obj = ((PyArray) obj).getArray();
    }

    if (obj instanceof List<?>) {
        @SuppressWarnings("unchecked")
        List<Object> jl = (List<Object>) obj;
        int l = jl.size();
        for (int i = 0; i < l; i++) {
            Object lo = jl.get(i);
            if (lo instanceof PyObject) {
                jl.set(i, convertToJava(lo));
            }
        }
        return obj;
    }

    if (obj.getClass().isArray()) {
        int l = Array.getLength(obj);
        for (int i = 0; i < l; i++) {
            Object lo = Array.get(obj, i);
            if (lo instanceof PyObject) {
                Array.set(obj, i, convertToJava(lo));
            }
        }
        return obj;
    }

    if (obj instanceof BigInteger || !(obj instanceof PyObject))
        return obj;

    if (obj instanceof PyComplex) {
        PyComplex z = (PyComplex) obj;
        return new Complex(z.real, z.imag);
    } else if (obj instanceof PyString) {
        return obj.toString();
    }

    return ((PyObject) obj).__tojava__(Object.class);
}

From source file:org.atemsource.atem.impl.common.attribute.collection.ArrayAttributeImpl.java

@Override
public Collection getElements(Object entity) {
    final Object array = getValue(entity);
    List arrayList = new ArrayList();
    if (array == null) {
        return null;
    } else {/*  www .  j a v  a  2 s.c  om*/
        for (int index = 0; index < Array.getLength(array); index++) {
            arrayList.add(Array.get(array, index));
        }
        return arrayList;
    }
}

From source file:org.datalorax.populace.core.populate.mutator.ensure.EnsureArrayElementsNotNullMutator.java

@Override
public Object mutate(Type type, Object currentValue, final Object parent, PopulatorContext config) {
    Validate.isTrue(TypeUtils.isArrayType(type), "Unsupported type %s", type);
    if (currentValue == null) {
        return null;
    }//  w ww.  java2 s  .  c o m

    final int length = Array.getLength(currentValue);
    if (length == 0) {
        return currentValue;
    }

    final Type valueType = getComponentType(type);

    for (int i = 0; i != length; ++i) {
        if (Array.get(currentValue, i) != null) {
            continue;
        }

        final Object instance = config.createInstance(valueType, null);
        Array.set(currentValue, i, instance);
    }
    return currentValue;
}

From source file:fi.jumi.core.util.EqualityMatchers.java

private static String findDifference(String path, Object obj1, Object obj2) {
    if (obj1 == null || obj2 == null) {
        return obj1 == obj2 ? null : path;
    }/*from w  w w . j  a va2  s  .c  om*/
    if (obj1.getClass() != obj2.getClass()) {
        return path;
    }

    // collections have a custom equals, but we want deep equality on every collection element
    // TODO: support other collection types? comparing Sets should be order-independent
    if (obj1 instanceof List) {
        List<?> col1 = (List<?>) obj1;
        List<?> col2 = (List<?>) obj2;

        int size1 = col1.size();
        int size2 = col2.size();
        if (size1 != size2) {
            return path + ".size()";
        }

        for (int i = 0; i < Math.min(size1, size2); i++) {
            String diff = findDifference(path + ".get(" + i + ")", col1.get(i), col2.get(i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // use custom equals method if exists
    try {
        Method equals = obj1.getClass().getMethod("equals", Object.class);
        if (equals.getDeclaringClass() != Object.class) {
            return obj1.equals(obj2) ? null : path;
        }
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    // arrays
    if (obj2.getClass().isArray()) {
        int length1 = Array.getLength(obj1);
        int length2 = Array.getLength(obj2);
        if (length1 != length2) {
            return path + ".length";
        }

        for (int i = 0; i < Math.min(length1, length2); i++) {
            String diff = findDifference(path + "[" + i + "]", Array.get(obj1, i), Array.get(obj2, i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // structural equality
    for (Class<?> cl = obj2.getClass(); cl != null; cl = cl.getSuperclass()) {
        for (Field field : cl.getDeclaredFields()) {
            try {
                String diff = findDifference(path + "." + field.getName(),
                        FieldUtils.readField(field, obj1, true), FieldUtils.readField(field, obj2, true));
                if (diff != null) {
                    return diff;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return null;
}

From source file:Main.java

public static Map<String, Object> getProperties(Object object, boolean includeSuperClasses, boolean deepCopy) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    if (object == null) {
        return map;
    }//from w  w  w  .  j  av a 2s .  com

    Class<?> objectClass = object.getClass();
    Method[] methods = includeSuperClasses ? objectClass.getMethods() : objectClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 0 && !method.getReturnType().equals(Void.TYPE)) {
            String methodName = method.getName();
            String propertyName = "";
            if (methodName.startsWith("get")) {
                propertyName = methodName.substring(3);
            } else if (methodName.startsWith("is")) {
                propertyName = methodName.substring(2);
            }
            if (propertyName.length() > 0 && Character.isUpperCase(propertyName.charAt(0))) {
                propertyName = Character.toLowerCase(propertyName.charAt(0)) + propertyName.substring(1);

                Object value = null;
                try {
                    value = method.invoke(object);
                } catch (Exception e) {
                }

                Object value2 = value;

                if (!deepCopy) {
                    map.put(propertyName, value);
                } else {
                    if (isSimpleObject(value)) {
                        map.put(propertyName, value);
                    } else if (value instanceof Map) {
                        Map<String, Object> submap = new HashMap<String, Object>();
                        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                            submap.put(String.valueOf(entry.getKey()),
                                    convertObject(entry.getValue(), includeSuperClasses));
                        }
                        map.put(propertyName, submap);
                    } else if (value instanceof Iterable) {
                        List<Object> sublist = new ArrayList<Object>();
                        for (Object v : (Iterable<?>) object) {
                            sublist.add(convertObject(v, includeSuperClasses));
                        }
                        map.put(propertyName, sublist);
                    } else if (value.getClass().isArray()) {
                        List<Object> sublist = new ArrayList<Object>();
                        int length = Array.getLength(value);
                        for (int i = 0; i < length; i++) {
                            sublist.add(convertObject(Array.get(value, i), includeSuperClasses));
                        }
                        map.put(propertyName, sublist);
                    } else {
                        map.put(propertyName, getProperties(value, includeSuperClasses, deepCopy));
                    }
                }
            }
        }
    }

    return map;
}

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * // w w  w  .ja va  2  s  .c  o m
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:ArrayDemo.java

/** 
 * Print out 2 arrays in columnar format.
 *
 * @param first The array for the first column.
 * @param second The array for the second column.
 *
 * @throws IllegalArgumentException __UNDOCUMENTED__
 *//*from www .j a  v a 2  s  .  c o  m*/
public static void outputArrays(final Object first, final Object second) {
    if (!first.getClass().isArray()) {
        throw new IllegalArgumentException("first is not an array.");
    }
    if (!second.getClass().isArray()) {
        throw new IllegalArgumentException("second is not an array.");
    }

    final int lengthFirst = Array.getLength(first);
    final int lengthSecond = Array.getLength(second);
    final int length = Math.max(lengthFirst, lengthSecond);

    for (int idx = 0; idx < length; idx++) {
        System.out.print("[" + idx + "]\t");
        if (idx < lengthFirst) {
            System.out.print(Array.get(first, idx) + "\t\t");
        } else {
            System.out.print("\t\t");
        }
        if (idx < lengthSecond) {
            System.out.print(Array.get(second, idx) + "\t");
        }
        System.out.println();
    }
}