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.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param value//from w w  w . ja  v a2 s . c  om
 * @return
 */
private static List<String> makeStringList(Object value) {
    if (value == null) {
        value = "";
    }
    List<String> result = new ArrayList<String>();
    if (value.getClass().isArray()) {
        for (int j = 0; j < Array.getLength(value); j++) {
            Object obj = Array.get(value, j);
            result.add(obj != null ? obj.toString() : "");
        }
        return result;
    }

    if (value instanceof Iterator) {
        Iterator it = (Iterator) value;
        while (it.hasNext()) {
            Object obj = it.next();
            result.add(obj != null ? obj.toString() : "");
        }
        return result;
    }

    if (value instanceof Collection) {
        for (Object obj : (Collection) value) {
            result.add(obj != null ? obj.toString() : "");
        }
        return result;
    }

    if (value instanceof Enumeration) {
        Enumeration enumeration = (Enumeration) value;
        while (enumeration.hasMoreElements()) {
            Object obj = enumeration.nextElement();
            result.add(obj != null ? obj.toString() : "");
        }
        return result;
    }
    result.add(value.toString());
    return result;
}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Same as assertEqualBeans, but works on protected and private fields.
 * //from   w  w  w.jav a 2 s  . c  om
 * @param lhs
 *            The initial object.
 * @param rhs
 *            The final object.
 * @param properties
 *            The properties to check.
 * @throws Exception
 */
public void assertEqualBeans2(Object lhs, Object rhs, String properties) throws Exception {
    assertNotNull("lhs is null", lhs);
    assertNotNull("rhs is null", rhs);
    for (String p : properties.split(",")) {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p);
        Object lp, rp;
        if (pd == null) {
            Field f = getField(lhs.getClass(), p);
            assertNotNull("No such property " + p + " on " + lhs.getClass(), f);
            boolean accessible = f.isAccessible();
            if (!accessible)
                f.setAccessible(true);
            lp = f.get(lhs);
            rp = f.get(rhs);
            f.setAccessible(accessible);
        } else {
            lp = PropertyUtils.getProperty(lhs, p);
            rp = PropertyUtils.getProperty(rhs, p);
        }

        if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) {
            // deep array equality comparison
            int m = Array.getLength(lp);
            int n = Array.getLength(rp);
            assertEquals("Array length is different for property " + p, m, n);
            for (int i = 0; i < m; i++)
                assertEquals(p + "[" + i + "] is different", Array.get(lp, i), Array.get(rp, i));
            return;
        }

        assertEquals("Property " + p + " is different", lp, rp);
    }
}

From source file:org.paxml.util.ReflectUtils.java

public static int collectArray(Object array, Collection col) {
    int len = Array.getLength(array);
    for (int i = 0; i < len; i++) {
        col.add(Array.get(array, i));
    }//from   w w  w  .  ja v a2 s  .  c om
    return len;
}

From source file:org.kuali.rice.core.web.format.Formatter.java

public Object formatArray(Object value) {
    // begin Kuali Foundation modification
    Class elementType = value.getClass().getComponentType();
    if (!isSupportedType(elementType))
        return value;

    int length = Array.getLength(value);
    Object[] formattedVals = new String[length];

    for (int i = 0; i < length; i++) {
        Object element = Array.get(value, i);
        Object objValue = ArrayUtils.toObject(element);
        Formatter elementFormatter = getFormatter(elementType);
        formattedVals[i] = elementFormatter.formatForPresentation(objValue);
    }//  w w  w .j ava2 s  . c o m

    return formattedVals;
    // end Kuali Foundation modification
}

From source file:org.jfree.chart.demo.SampleXYSymbolicDataset.java

/**
 * Returns a clone of the array./*from   ww  w.j av  a  2 s. co m*/
 * 
 * @param arr
 *           the array.
 * @return a clone.
 */
private static Object cloneArray(final Object arr) {

    if (arr == null) {
        return arr;
    }

    final Class cls = arr.getClass();
    if (!cls.isArray()) {
        return arr;
    }

    final int length = Array.getLength(arr);
    final Object[] newarr = (Object[]) Array.newInstance(cls.getComponentType(), length);

    Object obj;

    for (int i = 0; i < length; i++) {
        obj = Array.get(arr, i);
        if (obj.getClass().isArray()) {
            newarr[i] = cloneArray(obj);
        } else {
            newarr[i] = obj;
        }
    }

    return newarr;
}

From source file:com.sun.faces.el.PropertyResolverImpl.java

public Class getType(Object base, int index) {
    Class result = null;/*from   w  ww .  j a  v a 2 s.  c  om*/

    if (base == null) {
        throw new PropertyNotFoundException("Error setting index '" + index + "' in bean of type null");
    }

    try {
        // Try to read the index, to trigger exceptions if any
        if (base.getClass().isArray()) {
            Array.get(base, index);
            result = base.getClass().getComponentType();
        } else if (base instanceof List) {
            Object o = ((List) base).get(index);
            if (o != null) {
                result = o.getClass();
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("getValue:Property not found at index:" + index);
            }
            throw new EvaluationException(
                    "Bean of type " + base.getClass().getName() + " doesn't have indexed properties");
        }
    } catch (IndexOutOfBoundsException e) {
        throw new PropertyNotFoundException("Error getting index " + index, e);
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("getType:Error getting index:" + index);
        }
        throw new EvaluationException("Error getting index " + index, t);
    }
    return result;
}

From source file:net.sf.excelutils.ExcelParser.java

/**
 * get Iterator from the object//from w  w w. j  a  va  2  s . c om
 * 
 * @param collection
 * @return Iterator of the object
 */
public static Iterator getIterator(Object collection) {
    Iterator iterator = null;
    if (collection.getClass().isArray()) {
        try {
            // If we're lucky, it is an array of objects
            // that we can iterate over with no copying
            iterator = Arrays.asList((Object[]) collection).iterator();
        } catch (ClassCastException e) {
            // Rats -- it is an array of primitives
            int length = Array.getLength(collection);
            ArrayList c = new ArrayList(length);
            for (int i = 0; i < length; i++) {
                c.add(Array.get(collection, i));
            }
            iterator = c.iterator();
        }
    } else if (collection instanceof Collection) {
        iterator = ((Collection) collection).iterator();
    } else if (collection instanceof Iterator) {
        iterator = (Iterator) collection;
    } else if (collection instanceof Map) {
        iterator = ((Map) collection).entrySet().iterator();
    }
    return iterator;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Constructs an aggregate quad tree for an input HDF file on a selected
 * dataset identified by its name in the file.
 * @param conf The system configuration which can contain user-defined parameters.
 * @param inFile The path of the input HDF file to read
 * @param datasetName The name of the dataset to index in the HDF file
 * @param outFile The path to the index file to write
 * @throws IOException If an error happens while reading the input or writing the output
 *///w ww  .ja  v a2s.  c o m
public static void build(Configuration conf, Path inFile, String datasetName, Path outFile) throws IOException {
    FileSystem inFs = inFile.getFileSystem(conf);
    if (inFs instanceof HTTPFileSystem) {
        // HDF files are really bad to read over HTTP due to seeks
        inFile = new Path(FileUtil.copyFile(conf, inFile));
        inFs = FileSystem.getLocal(conf);
    }
    HDFFile hdfFile = null;
    try {
        hdfFile = new HDFFile(inFs.open(inFile));
        DDVGroup dataGroup = hdfFile.findGroupByName(datasetName);

        if (dataGroup == null)
            throw new RuntimeException("Cannot find dataset '" + datasetName + "' in file " + inFile);

        boolean fillValueFound = false;
        short fillValue = 0;
        short[] values = null;
        for (DataDescriptor dd : dataGroup.getContents()) {
            if (dd instanceof DDNumericDataGroup) {
                DDNumericDataGroup numericDataGroup = (DDNumericDataGroup) dd;
                values = (short[]) numericDataGroup.getAsTypedArray();
            } else if (dd instanceof DDVDataHeader) {
                DDVDataHeader vheader = (DDVDataHeader) dd;
                if (vheader.getName().equals("_FillValue")) {
                    fillValue = (short) (int) (Integer) vheader.getEntryAt(0);
                    fillValueFound = true;
                }
            }
        }

        // Retrieve meta data
        String archiveMetadata = (String) hdfFile.findHeaderByName("ArchiveMetadata.0").getEntryAt(0);
        String coreMetadata = (String) hdfFile.findHeaderByName("CoreMetadata.0").getEntryAt(0);
        NASADataset nasaDataset = new NASADataset(coreMetadata, archiveMetadata);

        if (values instanceof short[]) {
            FileSystem outFs = outFile.getFileSystem(conf);
            DataOutputStream out = new DataOutputStream(
                    new RandomCompressedOutputStream(outFs.create(outFile, false)));
            build(nasaDataset, (short[]) values, fillValue, out);
            out.close();
        } else {
            throw new RuntimeException("Indexing of values of type " + "'" + Array.get(values, 0).getClass()
                    + "' is not supported");
        }
    } finally {
        if (hdfFile != null)
            hdfFile.close();
    }
}

From source file:com.sm.query.utils.QueryUtils.java

/**
 * @param object/*from  w ww .  j a va  2s .  co m*/
 * @param metaData  - hashmap of ClassInfo
 * @return ClassInfo which represent
 * use getSimpleName() instead of getName()
 */
public static ClassInfo findClassInfo(Object object, Map<String, ClassInfo> metaData) {
    String className = object.getClass().getName();
    //getSimpleName without package name space
    String keyName = object.getClass().getSimpleName();
    ClassInfo info = metaData.get(keyName);
    if (info == null) {
        Type type = getType(className);
        Object obj;
        Collection values;
        switch (type) {
        case ARRAY:
            obj = Array.get(object, 0);
            //info = findClassInfo(object, cacheMetaData);
            assert (obj != null);
            info = findClassInfo(obj, metaData);
            break;
        case MAP:
            values = ((Map) object).values();
            obj = values.iterator().next();
            assert (obj != null);
            info = findClassInfo(obj, metaData);
            break;
        case HASHSET:
        case LIST:
            Iterator v = ((Collection) object).iterator();
            obj = v.next();
            info = findClassInfo(obj, metaData);
            break;
        case OBJECT:
            List<FieldInfo> list = new ArrayList<FieldInfo>();
            Class<?> cls = object.getClass();
            while (cls != null && cls != Object.class) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    if (!isSkipField(field)) {
                        field.setAccessible(true);
                        String fieldClsName = field.getType().getName();
                        Type fieldType = getType(fieldClsName);
                        list.add(new FieldInfo(field, fieldType, fieldClsName));
                    }
                }
                cls = cls.getSuperclass();
            }
            if (list.size() > 0) {
                FieldInfo[] fieldArray = new FieldInfo[list.size()];
                fieldArray = list.toArray(fieldArray);
                info = new ClassInfo(className, type, fieldArray);
            }
            break;
        default:
            logger.error("Wrong type =" + type + " in createClassInfo object className " + className
                    + " simple name " + keyName);
        } // switch

        metaData.put(keyName, info);
    }
    return info;

}

From source file:jef.tools.collection.CollectionUtil.java

/**
 * ??? ?Map?Collection/*w  w  w . ja  v a  2 s.  c o m*/
 * 
 * @param ?
 */
public static Object findElementInstance(Object collection) {
    if (collection == null)
        return null;
    if (collection.getClass().isArray()) {
        for (int i = 0; i < Array.getLength(collection); i++) {
            Object o = Array.get(collection, i);
            if (o != null) {
                return o;
            }
        }
    } else if (collection instanceof Collection) {
        for (Object o : ((Collection<?>) collection)) {
            if (o != null) {
                return o;
            }
        }
    }
    return null;
}