List of usage examples for java.lang.reflect Array get
public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:org.dcm4che3.conf.core.misc.DeepEquals.java
/** * Get a deterministic hashCode (int) value for an Object, regardless of * when it was created or where it was loaded into memory. The problem * with java.lang.Object.hashCode() is that it essentially relies on * memory location of an object (what identity it was assigned), whereas * this method will produce the same hashCode for any object graph, regardless * of how many times it is created.<br/><br/> * * This method will handle cycles correctly (A->B->C->A). In this case, * Starting with object A, B, or C would yield the same hashCode. If an * object encountered (root, suboject, etc.) has a hashCode() method on it * (that is not Object.hashCode()), that hashCode() method will be called * and it will stop traversal on that branch. * @param obj Object who hashCode is desired. * @return the 'deep' hashCode value for the passed in object. *///from ww w. j av a2 s . c o m public static int deepHashCode(Object obj) { Set visited = new HashSet(); LinkedList<Object> stack = new LinkedList<Object>(); stack.addFirst(obj); int hash = 0; while (!stack.isEmpty()) { obj = stack.removeFirst(); if (obj == null || visited.contains(obj)) { continue; } visited.add(obj); if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) { stack.addFirst(Array.get(obj, i)); } continue; } if (obj instanceof Collection) { stack.addAll(0, (Collection) obj); continue; } if (obj instanceof Map) { stack.addAll(0, ((Map) obj).keySet()); stack.addAll(0, ((Map) obj).values()); continue; } if (hasCustomHashCode(obj.getClass())) { // A real hashCode() method exists, call it. hash += obj.hashCode(); continue; } Collection<Field> fields = getDeepDeclaredFields(obj.getClass()); for (Field field : fields) { try { stack.addFirst(field.get(obj)); } catch (Exception ignored) { } } } return hash; }
From source file:com.github.jknack.handlebars.Context.java
/** * Resolve a array or list access using idx. * * @param current The current scope.//w w w. j a va 2 s. c o m * @param idx The index of the array or list. * @return An object at the given location or null. */ @SuppressWarnings("rawtypes") private Object resolveArrayAccess(final Object current, final String idx) { // It is a number, check if the current value is a index base object. int pos = Integer.parseInt(idx); try { if (current instanceof List) { return ((List) current).get(pos); } else if (current.getClass().isArray()) { return Array.get(current, pos); } } catch (IndexOutOfBoundsException exception) { // Index is outside of range, fallback to null as in handlebar.js return null; } return NULL; }
From source file:com.flexive.shared.FxFormatUtils.java
/** * Generic SQL escape method.//w w w . j a va 2s . c o m * * @param value the value to be formatted * @return the formatted value */ public static String escapeForSql(Object value) { if (value instanceof FxValue) { return ((FxValue) value).getSqlValue(); } else if (value instanceof String) { return "'" + StringUtils.replace((String) value, "'", "''") + "'"; } else if (value instanceof Date) { return "'" + new Formatter().format("%tF", (Date) value) + "'"; } else if (value instanceof FxSelectListItem) { return String.valueOf(((FxSelectListItem) value).getId()); } else if (value instanceof SelectMany) { final SelectMany selectMany = (SelectMany) value; final List<Long> selectedIds = selectMany.getSelectedIds(); if (selectedIds.size() > 1) { return "(" + StringUtils.join(selectedIds.iterator(), ',') + ")"; } else if (selectedIds.size() == 1) { return String.valueOf(selectedIds.get(0)); } else { return "-1"; } } else if (value != null && value.getClass().isArray()) { // decode array via reflection to support primitive arrays final List<Object> result = new ArrayList<Object>(); final int len = Array.getLength(value); for (int i = 0; i < len; i++) { result.add(Array.get(value, i)); } return makeTuple(result); } else if (value instanceof Collection) { return makeTuple((Collection) value); } else if (value != null) { return value.toString(); } else { return "null"; } }
From source file:gda.data.scan.datawriter.NexusDataWriter.java
private static int getIntfromBuffer(Object buf) { if (buf instanceof Object[]) buf = ((Object[]) buf)[0]; if (buf instanceof Number) return ((Number) buf).intValue(); if (buf.getClass().isArray()) { int len = ArrayUtils.getLength(buf); if (len == 1) { Object object = Array.get(buf, 0); return getIntfromBuffer(object); }// w ww .j av a2 s .c o m } return Integer.parseInt(buf.toString()); }
From source file:org.apache.torque.util.SqlExpression.java
/** * Takes a columnName and criteria (which must be an array) and builds a SQL 'IN' expression taking into account the ignoreCase * flag.// w ww. j ava 2 s.c o m * * @param columnName A column. * @param criteria The value to compare the column against. * @param comparison Either " IN " or " NOT IN ". * @param ignoreCase If true and columns represent Strings, the appropriate function defined for the database will be used to * ignore differences in case. * @param db Represents the database in use, for vendor specific functions. * @param whereClause A StringBuffer to which the sql expression will be appended. */ static void buildIn(String columnName, Object criteria, SqlEnum comparison, boolean ignoreCase, DB db, StringBuffer whereClause) { if (ignoreCase) { whereClause.append(db.ignoreCase(columnName)); } else { whereClause.append(columnName); } whereClause.append(comparison); HashSet inClause = new HashSet(); if (criteria instanceof List) { Iterator iter = ((List) criteria).iterator(); while (iter.hasNext()) { Object value = iter.next(); // The method processInValue() quotes the string // and/or wraps it in UPPER(). inClause.add(processInValue(value, ignoreCase, db)); } } else if (criteria instanceof String) { // subquery inClause.add(criteria); } else { // Assume array. for (int i = 0; i < Array.getLength(criteria); i++) { Object value = Array.get(criteria, i); // The method processInValue() quotes the string // and/or wraps it in UPPER(). inClause.add(processInValue(value, ignoreCase, db)); } } whereClause.append('(').append(StringUtils.join(inClause.iterator(), ",")).append(')'); }
From source file:org.eclipse.dataset.AbstractCompoundDataset.java
public static int[] toIntegerArray(final Object b, final int itemSize) { int[] result = null; if (b instanceof Number) { result = new int[itemSize]; int val = ((Number) b).intValue(); for (int i = 0; i < itemSize; i++) result[i] = val; } else if (b instanceof int[]) { result = (int[]) b; if (result.length < itemSize) { result = new int[itemSize]; int ilen = result.length; for (int i = 0; i < ilen; i++) result[i] = ((int[]) b)[i]; }/*from www .j a v a2 s . c o m*/ } else if (b instanceof List<?>) { result = new int[itemSize]; List<?> jl = (List<?>) b; int ilen = jl.size(); if (ilen > 0 && !(jl.get(0) instanceof Number)) { logger.error("Given array was not of a numerical primitive type"); throw new IllegalArgumentException("Given array was not of a numerical primitive type"); } ilen = Math.min(itemSize, ilen); for (int i = 0; i < ilen; i++) { result[i] = (int) toLong(jl.get(i)); } } else if (b.getClass().isArray()) { result = new int[itemSize]; int ilen = Array.getLength(b); if (ilen > 0 && !(Array.get(b, 0) instanceof Number)) { logger.error("Given array was not of a numerical primitive type"); throw new IllegalArgumentException("Given array was not of a numerical primitive type"); } ilen = Math.min(itemSize, ilen); for (int i = 0; i < ilen; i++) result[i] = (int) ((Number) Array.get(b, i)).longValue(); } else if (b instanceof Complex) { if (itemSize > 2) { logger.error("Complex number will not fit in compound dataset"); throw new IllegalArgumentException("Complex number will not fit in compound dataset"); } Complex cb = (Complex) b; switch (itemSize) { default: case 0: break; case 1: result = new int[] { (int) cb.getReal() }; break; case 2: result = new int[] { (int) cb.getReal(), (int) cb.getImaginary() }; break; } } else if (b instanceof Dataset) { Dataset db = (Dataset) b; if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toIntegerArray(db.getObjectAbs(0), itemSize); } else if (b instanceof IDataset) { IDataset db = (Dataset) b; if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toIntegerArray(db.getObject(new int[db.getRank()]), itemSize); } return result; }
From source file:com.flexive.faces.FxJsfComponentUtils.java
/** * Check if the given array contains an actual value * * @param valueArray value array/*from w w w. j a v a 2 s . c o m*/ * @return if an actual value is set in the array */ public static boolean containsaValue(Object valueArray) { if (null != valueArray) { int len = Array.getLength(valueArray); for (int i = 0; i < len; i++) { Object value = Array.get(valueArray, i); if (value != null && !(value.equals(FxSelectRenderer.NO_VALUE))) { return true; } } } return false; }
From source file:org.eclipse.january.dataset.DTypeUtils.java
public static double toImag(final Object b) { if (b instanceof Number) { return 0; } else if (b instanceof Boolean) { return 0; } else if (b instanceof Complex) { return ((Complex) b).getImaginary(); } else if (b.getClass().isArray()) { if (Array.getLength(b) < 2) return 0; return toReal(Array.get(b, 1)); } else if (b instanceof Dataset) { Dataset db = (Dataset) b;/*from ww w . j a v a 2 s . co m*/ if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toImag(db.getObjectAbs(0)); } else if (b instanceof IDataset) { IDataset db = (Dataset) b; if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toImag(db.getObject(new int[db.getRank()])); } else { logger.error("Argument is of unsupported class"); throw new IllegalArgumentException("Argument is of unsupported class"); } }
From source file:com.espertech.esper.support.util.ArrayAssertionUtil.java
private static Object[] toObjectArray(Object array) { if ((array == null) || (!array.getClass().isArray())) { throw new IllegalArgumentException("Object not an array but type '" + array.getClass() + "'"); }//w w w. j a va2 s . c o m int size = Array.getLength(array); Object[] val = new Object[size]; for (int i = 0; i < size; i++) { val[i] = Array.get(array, i); } return val; }
From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java
/** * Gets the bean size intern./*from w w w .j av a2s . c om*/ * * @param bean the bean * @param clazz the clazz * @param m the m * @param classNameMatcher the class name matcher * @param fieldNameMatcher the field name matcher * @return the bean size intern */ public static int getBeanSizeIntern(Object bean, Class<?> clazz, IdentityHashMap<Object, Object> m, Matcher<String> classNameMatcher, Matcher<String> fieldNameMatcher) { if (classNameMatcher.match(clazz.getName()) == false) { return 0; } if (clazz.isArray() == true) { if (clazz == boolean[].class) { return (((boolean[]) bean).length * 4); } else if (clazz == char[].class) { return (((char[]) bean).length * 2); } else if (clazz == byte[].class) { return (((byte[]) bean).length * 1); } else if (clazz == short[].class) { return (((short[]) bean).length * 2); } else if (clazz == int[].class) { return (((int[]) bean).length * 4); } else if (clazz == long[].class) { return (((long[]) bean).length * 4); } else if (clazz == float[].class) { return (((float[]) bean).length * 4); } else if (clazz == double[].class) { return (((double[]) bean).length * 8); } else { int length = Array.getLength(bean); int ret = (length * 4); for (int i = 0; i < length; ++i) { ret += getBeanSize(Array.get(bean, i), m, classNameMatcher, fieldNameMatcher); } return ret; } } int ret = 0; try { for (Field f : clazz.getDeclaredFields()) { int mod = f.getModifiers(); if (Modifier.isStatic(mod) == true) { continue; } if (fieldNameMatcher.match(clazz.getName() + "." + f.getName()) == false) { continue; } if (f.getType() == Boolean.TYPE) { ret += 4; } else if (f.getType() == Character.TYPE) { ret += 2; } else if (f.getType() == Byte.TYPE) { ret += 1; } else if (f.getType() == Short.TYPE) { ret += 2; } else if (f.getType() == Integer.TYPE) { ret += 4; } else if (f.getType() == Long.TYPE) { ret += 8; } else if (f.getType() == Float.TYPE) { ret += 4; } else if (f.getType() == Double.TYPE) { ret += 8; } else { ret += 4; Object o = null; try { o = readField(bean, f); if (o == null) { continue; } } catch (NoClassDefFoundError ex) { // nothing continue; } int nestedsize = getBeanSize(o, o.getClass(), m, classNameMatcher, fieldNameMatcher); ret += nestedsize; } } } catch (NoClassDefFoundError ex) { // ignore here. } if (clazz == Object.class || clazz.getSuperclass() == null) { return ret; } ret += getBeanSizeIntern(bean, clazz.getSuperclass(), m, classNameMatcher, fieldNameMatcher); return ret; }