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:com.mawujun.util.ObjectUtils.java
/** * <p>Clone an object.</p>/* ww w .j a v a 2 s .c o m*/ * * @param <T> the type of the object * @param obj the object to clone, null returns null * @return the clone if the object implements {@link Cloneable} otherwise {@code null} * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 3.0 */ public static <T> T clone(final T obj) { if (obj instanceof Cloneable) { final Object result; if (obj.getClass().isArray()) { final Class<?> componentType = obj.getClass().getComponentType(); if (!componentType.isPrimitive()) { result = ((Object[]) obj).clone(); } else { int length = Array.getLength(obj); result = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(result, length, Array.get(obj, length)); } } } else { try { final Method clone = obj.getClass().getMethod("clone"); result = clone.invoke(obj); } catch (final NoSuchMethodException e) { throw new CloneFailedException( "Cloneable type " + obj.getClass().getName() + " has no clone method", e); } catch (final IllegalAccessException e) { throw new CloneFailedException("Cannot clone Cloneable type " + obj.getClass().getName(), e); } catch (final InvocationTargetException e) { throw new CloneFailedException("Exception cloning Cloneable type " + obj.getClass().getName(), e.getCause()); } } @SuppressWarnings("unchecked") final T checked = (T) result; return checked; } return null; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * If array, get the element based on index, if Collection, get it based on * iterator./*from ww w. ja va 2s .co m*/ * * @param arrayOrCollection * @param iterator * @param index * @return the object */ public static Object next(Object arrayOrCollection, Iterator iterator, int index) { if (arrayOrCollection.getClass().isArray()) { return Array.get(arrayOrCollection, index); } if (arrayOrCollection instanceof ArrayList) { return ((ArrayList) arrayOrCollection).get(index); } if (arrayOrCollection instanceof Collection) { return iterator.next(); } // simple object if (0 == index) { return arrayOrCollection; } throw new RuntimeException("Invalid class type: " + arrayOrCollection.getClass().getName()); }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * Asserts that two JavaBeans are equal as far as the given list of properties are concerned. * * <p>//from ww w.j a va2 s . c o m * This method takes two objects that have properties (getXyz, isXyz, or just the public xyz field), * and makes sure that the property values for each given property are equals (by using {@link org.junit.Assert#assertThat(Object, org.hamcrest.Matcher)}) * * <p> * Property values can be null on both objects, and that is OK, but passing in a property that doesn't * exist will fail an assertion. * * <p> * This method is very convenient for comparing a large number of properties on two objects, * for example to verify that the configuration is identical after a config screen roundtrip. * * @param lhs * One of the two objects to be compared. * @param rhs * The other object to be compared * @param properties * ','-separated list of property names that are compared. * @since 1.297 */ public void assertEqualBeans(Object lhs, Object rhs, String properties) throws Exception { assertThat("LHS", lhs, notNullValue()); assertThat("RHS", rhs, notNullValue()); for (String p : properties.split(",")) { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p); Object lp, rp; if (pd == null) { // field? try { Field f = lhs.getClass().getField(p); lp = f.get(lhs); rp = f.get(rhs); } catch (NoSuchFieldException e) { assertThat("No such property " + p + " on " + lhs.getClass(), pd, notNullValue()); return; } } 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); assertThat("Array length is different for property " + p, n, is(m)); for (int i = 0; i < m; i++) assertThat(p + "[" + i + "] is different", Array.get(rp, i), is(Array.get(lp, i))); return; } assertThat("Property " + p + " is different", rp, is(lp)); } }
From source file:org.eclipse.january.dataset.DatasetUtils.java
private static void setRow(Object row, Dataset a, int... pos) { final int l = Array.getLength(row); final int rank = pos.length; final int[] npos = Arrays.copyOf(pos, rank + 1); Object r;// ww w . java2 s . co m if (rank + 1 < a.getRank()) { for (int i = 0; i < l; i++) { npos[rank] = i; r = Array.get(row, i); setRow(r, a, npos); } } else { for (int i = 0; i < l; i++) { npos[rank] = i; r = a.getObject(npos); Array.set(row, i, r); } } }
From source file:com.github.crab2died.ExcelUtils.java
private void generateSheet(Workbook workbook, List<?> data, List<String> header, String sheetName) { Sheet sheet;// w w w .j a va 2 s.co m if (null != sheetName && !"".equals(sheetName)) { sheet = workbook.createSheet(sheetName); } else { sheet = workbook.createSheet(); } int rowIndex = 0; if (null != header && header.size() > 0) { // Row row = sheet.createRow(rowIndex++); for (int i = 0; i < header.size(); i++) { row.createCell(i, CellType.STRING).setCellValue(header.get(i)); } } for (Object object : data) { Row row = sheet.createRow(rowIndex++); if (object.getClass().isArray()) { for (int j = 0; j < Array.getLength(object); j++) { row.createCell(j, CellType.STRING).setCellValue(Array.get(object, j).toString()); } } else if (object instanceof Collection) { Collection<?> items = (Collection<?>) object; int j = 0; for (Object item : items) { row.createCell(j++, CellType.STRING).setCellValue(item.toString()); } } else { row.createCell(0, CellType.STRING).setCellValue(object.toString()); } } }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property./*from w ww. j a v a 2 s . com*/ * @param propertyName name of the property * @param oldValue previous value, if available (may be <code>null</code>) * @param newValue proposed change value * @param requiredType the type we must convert to * (or <code>null</code> if not known, for example in case of a collection element) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ protected Object doTypeConversionIfNecessary(String propertyName, String fullPropertyName, Object oldValue, Object newValue, Class requiredType) throws TypeMismatchException { Object convertedValue = newValue; if (convertedValue != null) { // Custom editor for this type? PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName); // Value not of required type? if (pe != null || (requiredType != null && (requiredType.isArray() || !requiredType.isAssignableFrom(convertedValue.getClass())))) { if (requiredType != null) { if (pe == null) { // No custom editor -> check BeanWrapperImpl's default editors. pe = (PropertyEditor) this.defaultEditors.get(requiredType); if (pe == null) { // No BeanWrapper default editor -> check standard JavaBean editors. pe = PropertyEditorManager.findEditor(requiredType); } } } if (pe != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { pe.setValue(convertedValue); Object newConvertedValue = pe.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. pe = null; } } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isDebugEnabled()) { logger.debug("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); } if (pe != null && convertedValue instanceof String) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isDebugEnabled()) { logger.debug( "Converting String to [" + requiredType + "] using property editor [" + pe + "]"); } try { pe.setValue(oldValue); pe.setAsText((String) convertedValue); convertedValue = pe.getValue(); } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null) { // Array required -> apply appropriate conversion of elements. if (requiredType.isArray()) { Class componentType = requiredType.getComponentType(); if (convertedValue instanceof Collection) { // Convert Collection elements to array elements. Collection coll = (Collection) convertedValue; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator it = coll.iterator(); it.hasNext(); i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, it.next(), componentType); Array.set(result, i, value); } return result; } else if (convertedValue != null && convertedValue.getClass().isArray()) { // Convert Collection elements to array elements. int arrayLength = Array.getLength(convertedValue); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, Array.get(convertedValue, i), componentType); Array.set(result, i, value); } return result; } else { // A plain value: convert it to an array with a single component. Object result = Array.newInstance(componentType, 1); Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX, null, convertedValue, componentType); Array.set(result, 0, value); return result; } } // If the resulting value definitely doesn't match the required type, // try field lookup as fallback. If no matching field found, // throw explicit TypeMismatchException with full context information. if (convertedValue != null && !requiredType.isPrimitive() && !requiredType.isAssignableFrom(convertedValue.getClass())) { // In case of String value, try to find matching field (for JDK 1.5 // enum or custom enum with values defined as static fields). if (convertedValue instanceof String) { try { Field enumField = requiredType.getField((String) convertedValue); return enumField.get(null); } catch (Exception ex) { logger.debug("Field [" + convertedValue + "] isn't an enum value", ex); } } // Definitely doesn't match: throw TypeMismatchException. throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType); } } } } if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod() .getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualType instanceof Class && convertedValue != null) { List list = (List) convertedValue; for (int i = 0; i < list.size(); i++) { Object o = list.remove(i); o = doTypeConversionIfNecessary(o, (Class) actualType); list.add(i, o); } } } } return convertedValue; }
From source file:kx.c.java
/** * Gets the object at an index of an array * /* ww w. ja v a 2s .c o m*/ * @param x The array to index * @param i The offset to index at * @return object at index */ public static Object at(Object x, int i) { return qn(x = Array.get(x, i)) ? null : x; }
From source file:com.servoy.j2db.util.Utils.java
public final static boolean equalObjects(Object oldObj, Object obj, double equalsPrecision, boolean ignoreCase) { if (oldObj instanceof Wrapper) oldObj = ((Wrapper) oldObj).unwrap(); if (obj instanceof Wrapper) obj = ((Wrapper) obj).unwrap(); if (oldObj == obj) { return true; }// w w w . j ava2 s .c o m if (oldObj == null && obj != null) { return false; } if (oldObj != null && obj == null) { return false; } // Compare UUID with possible storage for UUID if (oldObj.getClass() == UUID.class) { if (obj.getClass() == byte[].class && ((byte[]) obj).length == 16) { // compare UUID and byte[] return oldObj.equals(new UUID((byte[]) obj)); } if (obj.getClass() == String.class && ((String) obj).length() == 36) { // compare UUID and String return oldObj.toString().equals(obj); } return oldObj.equals(obj); } if (obj.getClass() == UUID.class) { if (oldObj.getClass() == byte[].class && ((byte[]) oldObj).length == 16) { // compare UUID and byte[] return obj.equals(new UUID((byte[]) oldObj)); } if (oldObj.getClass() == String.class && ((String) oldObj).length() == 36) { // compare UUID and String return obj.toString().equals(oldObj); } return obj.equals(oldObj); } if (oldObj.getClass().isArray() && obj.getClass().isArray()) { int length = Array.getLength(obj); if (length == Array.getLength(oldObj)) { for (int i = 0; i < length; i++) { if (!equalObjects(Array.get(obj, i), Array.get(oldObj, i), equalsPrecision, ignoreCase)) return false; } return true; } return false; } //in case one side is String and other Number -> make both string if (oldObj instanceof Number && obj instanceof String) { try { obj = new Double((String) obj); } catch (Exception e) { oldObj = oldObj.toString(); } } else if (obj instanceof Number && oldObj instanceof String) { try { oldObj = new Double((String) oldObj); } catch (Exception e) { obj = obj.toString(); } } if (oldObj instanceof BigDecimal && !(obj instanceof BigDecimal)) { if (obj instanceof Long) { obj = BigDecimal.valueOf(((Long) obj).longValue()); } else if (obj instanceof Double) { obj = BigDecimal.valueOf(((Double) obj).doubleValue()); } } else if (obj instanceof BigDecimal && !(oldObj instanceof BigDecimal)) { if (oldObj instanceof Long) { oldObj = BigDecimal.valueOf(((Long) oldObj).longValue()); } else if (oldObj instanceof Double) { oldObj = BigDecimal.valueOf(((Double) oldObj).doubleValue()); } } // separate tests for BigDecimal and Long, the tests based on Double may give // incorrect results for Long values not fitting in a double mantissa. // note that 2.0 is not equal to 2.00 according to BigDecimal.equals() if (oldObj instanceof BigDecimal && obj instanceof BigDecimal) { return ((BigDecimal) oldObj).subtract((BigDecimal) obj).abs().doubleValue() < equalsPrecision; } if (oldObj instanceof Long && obj instanceof Long) { return oldObj.equals(obj); } // Always cast to double so we don't lose precision. if (oldObj instanceof Number && obj instanceof Number) { if (oldObj instanceof Float || oldObj instanceof Double || oldObj instanceof BigDecimal || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal) { double a = ((Number) oldObj).doubleValue(); double b = ((Number) obj).doubleValue(); return a == b || Math.abs(a - b) < equalsPrecision; } return ((Number) oldObj).longValue() == ((Number) obj).longValue(); } if (oldObj instanceof Date && obj instanceof Date) { return (((Date) oldObj).getTime() == ((Date) obj).getTime()); } if (ignoreCase && oldObj instanceof String && obj instanceof String) { return ((String) oldObj).equalsIgnoreCase((String) obj); } return oldObj.equals(obj); }
From source file:edu.stanford.muse.util.Util.java
/** * converts an object to a string->string map by converting all its fields * (fields may be non-public//from w w w . ja v a 2 s. c o m * if running without security manager). expand=true expands collections * (array, list, map) */ public static Map<String, String> convertObjectToMap(Object o, boolean expand) { Map<String, String> map = new LinkedHashMap<String, String>(); if (o == null) return map; Class c = o.getClass(); try { // generate a string to string map of the fields Field f[] = c.getDeclaredFields(); for (int i = 0; i < f.length; i++) { boolean acc = f[i].isAccessible(); if (!acc) f[i].setAccessible(true); // ok to do in absence of a security manager Class t = f[i].getType(); String name = f[i].getName(); if (name.indexOf("$") >= 0) // outer class, skip" + continue; if (t == double.class) map.put(name, Double.toString(f[i].getDouble(o))); else if (t == float.class) map.put(name, Float.toString(f[i].getFloat(o))); else if (t == int.class) map.put(name, Integer.toString(f[i].getInt(o))); else if (t == long.class) map.put(name, Long.toString(f[i].getLong(o))); else if (t == char.class) map.put(name, f[i].getChar(o) + "(" + Integer.toString(f[i].getChar(o)) + ")"); else if (t == short.class) map.put(name, Short.toString(f[i].getShort(o))); else if (t == byte.class) map.put(name, Byte.toString(f[i].getByte(o))); else if (t == boolean.class) map.put(name, Boolean.toString(f[i].getBoolean(o))); else { // field is of object type Object val = f[i].get(o); // o.f[i]'s type is t, value is // val if (val == null) map.put(name, "null"); else { Class valClass = val.getClass(); if (valClass.isArray()) { if (expand) for (int x = 0; x < Array.getLength(val); x++) map.put(name + "[" + x + "]", Array.get(val, x) + ""); } else if (java.util.Map.class.isAssignableFrom(valClass)) // could // also // check // t, // but // val.getClass // is // more // specific { Map m = (Map) f[i].get(o); if (expand) for (Object x : m.keySet()) map.put(name + "." + x, m.get(x) + ""); } // could also check t, but val.getClass is more specific else if (java.util.Collection.class.isAssignableFrom(valClass)) { Collection c1 = (Collection) f[i].get(o); if (expand) { int count = 0; for (Object o1 : c1) map.put(name + "(" + count++ + ")", o1 + ""); // use // () // instead // of // [] // to // distinguish // from // arrays } } else map.put(name, "[" + val.toString() + "]"); } } if (!acc) f[i].setAccessible(false); } } catch (Throwable e) { Util.print_exception(e); } return map; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * helper method to clone the value of a field. just returns the same * reference for primitives and immutables. Will subclone GrouperCloneables, * and will throw exception if not expecting the type. Will clone sets, lists, maps. * @param <T> template/*from ww w. jav a 2 s .c o m*/ * * @param value * @return the cloned value */ @SuppressWarnings("unchecked") public static <T> T cloneValue(T value) { Object clonedValue = value; if (value == null || value instanceof String || value.getClass().isPrimitive() || value instanceof Number || value instanceof Boolean || value instanceof Date) { //clone things //for strings, and immutable classes, just assign //nothing to do, just assign the value } else if (value instanceof Map) { clonedValue = new LinkedHashMap(); Map mapValue = (Map) value; Map clonedMapValue = (Map) clonedValue; for (Object key : mapValue.keySet()) { clonedMapValue.put(cloneValue(key), cloneValue(mapValue.get(key))); } } else if (value instanceof Set) { clonedValue = new LinkedHashSet(); Set setValue = (Set) value; Set clonedSetValue = (Set) clonedValue; for (Object each : setValue) { clonedSetValue.add(cloneValue(each)); } } else if (value instanceof List) { clonedValue = new ArrayList(); List listValue = (List) value; List clonedListValue = (List) clonedValue; for (Object each : listValue) { clonedListValue.add(cloneValue(each)); } } else if (value.getClass().isArray()) { clonedValue = Array.newInstance(value.getClass().getComponentType(), Array.getLength(value)); for (int i = 0; i < Array.getLength(value); i++) { Array.set(clonedValue, i, cloneValue(Array.get(value, i))); } } else { //this means lets add support for a new type of object throw new RuntimeException("Unexpected class in clone method: " + value.getClass()); } return (T) clonedValue; }