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.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * print out various types of objects//from w w w . j a v a 2 s.c om * * @param object * @param maxChars is where it should stop when figuring out object. note, result might be longer than max... * need to abbreviate when back * @param result is where to append to */ @SuppressWarnings("unchecked") private static void toStringForLogHelper(Object object, int maxChars, StringBuilder result) { try { if (object == null) { result.append("null"); } else if (object.getClass().isArray()) { // handle arrays int length = Array.getLength(object); if (length == 0) { result.append("Empty array"); } else { result.append("Array size: ").append(length).append(": "); for (int i = 0; i < length; i++) { result.append("[").append(i).append("]: ").append(Array.get(object, i)).append("\n"); if (maxChars != -1 && result.length() > maxChars) { return; } } } } else if (object instanceof Collection) { //give size and type if collection Collection<Object> collection = (Collection<Object>) object; int collectionSize = collection.size(); if (collectionSize == 0) { result.append("Empty ").append(object.getClass().getSimpleName()); } else { result.append(object.getClass().getSimpleName()).append(" size: ").append(collectionSize) .append(": "); int i = 0; for (Object collectionObject : collection) { result.append("[").append(i).append("]: ").append(collectionObject).append("\n"); if (maxChars != -1 && result.length() > maxChars) { return; } i++; } } } else { result.append(object.toString()); } } catch (Exception e) { result.append("<<exception>> ").append(object.getClass()).append(":\n").append(getFullStackTrace(e)) .append("\n"); } }
From source file:ArrayUtils.java
/** * Like {@link #equals(Object, Object)}, but compares arrays without regard * to order and uses an independent checker to check for equality of * elements/* w w w . j a v a 2s. c o m*/ * * @param o1 * The first object to compare * @param o2 * The second object to compare * @param checker * The checker to check elements for equality * @return true if <code>o1</code> and <code>o2</code> are arrays and their * elements are equivalent or if either * <code>o1==null && o2==null</code> or <code>o1.equals(o2)</code>, * false otherwise */ public static boolean equalsUnordered(Object o1, Object o2, EqualsChecker checker) { if (o1 == null) return o2 == null; if (o2 == null) return false; if (o1 instanceof Object[] && o2 instanceof Object[]) return equalsUnordered((Object[]) o1, (Object[]) o2, checker); if (o1.getClass().isArray() && o2.getClass().isArray()) { if (!o1.getClass().equals(o2.getClass())) return false; int len = Array.getLength(o1); if (len != Array.getLength(o2)) return false; if (len == 0) return true; long[] bs = new long[(len - 1) / 64 + 1]; long mask; int i, j, bsIdx; o1Loop: for (i = 0; i < len; i++) { mask = 0; for (j = 0; j < len; j++) { bsIdx = j / 64; if (mask == 0) mask = 0x8000000000000000L; if ((bs[bsIdx] & mask) == 0 && checker.equals(Array.get(o1, i), Array.get(o2, j))) { bs[bsIdx] |= mask; continue o1Loop; } mask >>>= 1; } return false; } return true; } return checker.equals(o1, o2); }
From source file:com.greenlaw110.rythm.toString.ToStringStyle.java
/** * <p>Append to the <code>toString</code> the detail of an array type.</p> * * @param buffer the <code>StringBuilder</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code>// www .j av a 2 s . co m * @since 2.0 */ protected void reflectionAppendArrayDetail(StringBuilder buffer, String fieldName, Object array) { buffer.append(arrayStart); int length = Array.getLength(array); for (int i = 0; i < length; i++) { Object item = Array.get(array, i); if (i > 0) { buffer.append(arraySeparator); } if (item == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, item, arrayContentDetail); } } buffer.append(arrayEnd); }
From source file:ArrayUtils.java
/** * A compliment to the {@link #equals(Object, Object)} method, this method * returns a hashcode for <code>array</code> such that it is consistent with * the equals contract for the {@link Object#equals(Object)} method, * represented by the {@link #equals(Object, Object)} method. * //from w w w .j a v a2 s . c o m * @param array * The array to get a hashcode for * @return A hashcode based on <code>array</code> and its contents, if any */ public static int hashCode(Object array) { if (array == null) return 0; if (!array.getClass().isArray()) return array.hashCode(); int ret = array.getClass().getComponentType().hashCode(); int len = Array.getLength(array); for (int i = 0; i < len; i++) { ret *= hashCode(Array.get(array, i)); ret += 29; } return ret; }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }/*from w w w . j av a 2s. c o m*/ if (logger.isDebugEnabled()) logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class [" + this.object.getClass().getName() + "]"); try { Object value = pd.getReadMethod().invoke(this.object, (Object[]) null); Type genericReturnType = pd.getReadMethod().getGenericReturnType(); Class rawReturnType = pd.getReadMethod().getReturnType(); if (tokens.keys != null) { // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; //cria listas sob demanda.. no mais necessrio utilizar o ListSet no pojo Class originalClass = null; if (value != null) { originalClass = value.getClass(); } if (value == null && rawReturnType != null && genericReturnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericReturnType; if (Map.class.isAssignableFrom(rawReturnType)) { value = new LinkedHashMap(); pd.getWriteMethod().invoke(this.object, value); } else if (List.class.isAssignableFrom(rawReturnType) || Set.class.isAssignableFrom(rawReturnType)) { Type type = parameterizedType.getActualTypeArguments()[0]; value = new ListSet(type instanceof Class ? (Class) type : (Class) ((ParameterizedType) type).getRawType()); pd.getWriteMethod().invoke(this.object, value); } } //fim da criacao sob demanda if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { value = Array.get(value, Integer.parseInt(key)); } else if (value instanceof List) { List list = (List) value; try { value = list.get(Integer.parseInt(key)); } catch (IndexOutOfBoundsException e) { //tentar instanciar um bean da lista String extraMessage = ""; if (genericReturnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericReturnType; Type type = parameterizedType.getActualTypeArguments()[0]; if (type instanceof Class) { Class clazz = (Class) type; extraMessage = "A classe " + clazz.getName() + " no possui um construtor publico sem argumentos"; try { value = clazz.newInstance(); int index = Integer.parseInt(key); int insertNulls = index - list.size(); while (insertNulls > 0) { // 11/06/2012 list.add(null); insertNulls--; } list.add(index, value); // CDIGO 15/01/2007 } catch (InstantiationException e1) { throw new RuntimeException( "Aconteceu um erro ao acessar um elemento da classe " + originalClass.getName() + " propriedade " + propertyName + " No foi possvel instanciar um bean para preencher a lista. " + extraMessage, e); } } } else if (originalClass != null) { throw new RuntimeException("Aconteceu um erro ao acessar um elemento da classe " + originalClass.getName() + " propriedade " + propertyName + " Sugesto: Utilize uma lista que cresa quando for necessrio como o ListSet ou no instancie nenhum objeto para essa propriedade", e); } else { throw e; } } } else if (value instanceof Set) { // apply index to Iterator in case of a Set //TODO CRIAR AUTOMATICAMENTE O BEAN DO SET Set set = (Set) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'" + " Sugesto: Utilize o ListSet ou no instancie nenhum objeto"); } Iterator it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { if (!(genericReturnType instanceof ParameterizedType)) { throw new NotParameterizedTypeException( "Path direciona a um Map no parameterizado com generics. " + " Propriedade '" + this.nestedPath + propertyName + "' da classe [" + this.rootObject.getClass().getName() + "]"); } ParameterizedType parameterizedType = ((ParameterizedType) genericReturnType); Type mapKeyType = parameterizedType.getActualTypeArguments()[0]; Type mapValueType = parameterizedType.getActualTypeArguments()[1]; Class rawKeyType = mapKeyType instanceof Class ? (Class) mapKeyType : (Class) ((ParameterizedType) mapKeyType).getRawType(); Class rawValueType = mapValueType instanceof Class ? (Class) mapValueType : (Class) ((ParameterizedType) mapValueType).getRawType(); Object objectKey = doTypeConversionIfNecessary(key, rawKeyType); Map map = (Map) value; value = map.get(objectKey); if (value == null && List.class.isAssignableFrom(rawValueType)) { List mapValue; try { Type listType = ((ParameterizedType) mapValueType).getActualTypeArguments()[0]; mapValue = new ListSet(listType instanceof Class ? (Class) listType : (Class) ((ParameterizedType) listType).getRawType()); } catch (ClassCastException e) { throw new RuntimeException( "Na path " + propertyName + " um mapa contm uma lista no parametrizada"); } map.put(objectKey, mapValue); value = mapValue; } } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } } } return value; } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (IllegalAccessException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } }
From source file:org.batoo.common.util.ObjectUtils.java
/** * Convert the given array (which may be a primitive array) to an object array (if necessary of primitive wrapper objects). * <p>/*from w w w .j av a 2s.c o m*/ * A <code>null</code> source value will be converted to an empty Object array. * * @param source * the (potentially primitive) array * @return the corresponding object array (never <code>null</code>) * @throws IllegalArgumentException * if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } final int length = Array.getLength(source); if (length == 0) { return new Object[0]; } final Class<?> wrapperType = Array.get(source, 0).getClass(); final Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }/*from ww w. j av a 2s. c o m*/ final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }
From source file:ArrayUtils.java
/** * A utility method for printing out the contents of an array (not deeply) * //from w w w . j a va 2 s . co m * @param array * The array to print * @return A String containing the representation of the contents of * <code>array</code> */ public static String toString(Object array) { if (array == null) return "" + null; else if (array instanceof Object[]) { Object[] oa = (Object[]) array; StringBuffer ret = new StringBuffer("["); for (int i = 0; i < oa.length; i++) { ret.append(toString(oa[i])); if (i < oa.length - 1) ret.append(", "); } ret.append("]"); return ret.toString(); } else if (array.getClass().isArray()) { StringBuffer ret = new StringBuffer("["); int len = Array.getLength(array); for (int i = 0; i < len; i++) { ret.append(Array.get(array, i)); if (i < len - 1) ret.append(", "); } ret.append("]"); return ret.toString(); } else return array.toString(); }
From source file:com.espertech.esper.filter.FilterSpecCompiler.java
private static FilterSpecParam handleInSetNode(ExprInNode constituent, LinkedHashMap<String, Pair<EventType, String>> arrayEventTypes, ExprEvaluatorContext exprEvaluatorContext, String statementName) throws ExprValidationException { ExprNode left = constituent.getChildNodes()[0]; if (!(left instanceof ExprFilterOptimizableNode)) { return null; }//from w w w . j a va 2 s . c om ExprFilterOptimizableNode filterOptimizableNode = (ExprFilterOptimizableNode) left; FilterSpecLookupable lookupable = filterOptimizableNode.getFilterLookupable(); FilterOperator op = FilterOperator.IN_LIST_OF_VALUES; if (constituent.isNotIn()) { op = FilterOperator.NOT_IN_LIST_OF_VALUES; } int expectedNumberOfConstants = constituent.getChildNodes().length - 1; List<FilterSpecParamInValue> listofValues = new ArrayList<FilterSpecParamInValue>(); Iterator<ExprNode> it = Arrays.asList(constituent.getChildNodes()).iterator(); it.next(); // ignore the first node as it's the identifier while (it.hasNext()) { ExprNode subNode = it.next(); if (ExprNodeUtility.isConstantValueExpr(subNode)) { ExprConstantNode constantNode = (ExprConstantNode) subNode; Object constant = constantNode.evaluate(null, true, exprEvaluatorContext); if (constant instanceof Collection) { return null; } if (constant instanceof Map) { return null; } if ((constant != null) && (constant.getClass().isArray())) { for (int i = 0; i < Array.getLength(constant); i++) { Object arrayElement = Array.get(constant, i); Object arrayElementCoerced = handleConstantsCoercion(lookupable, arrayElement); listofValues.add(new InSetOfValuesConstant(arrayElementCoerced)); if (i > 0) { expectedNumberOfConstants++; } } } else { constant = handleConstantsCoercion(lookupable, constant); listofValues.add(new InSetOfValuesConstant(constant)); } } if (subNode instanceof ExprContextPropertyNode) { ExprContextPropertyNode contextPropertyNode = (ExprContextPropertyNode) subNode; Class returnType = contextPropertyNode.getType(); if (JavaClassHelper.isImplementsInterface(contextPropertyNode.getType(), Collection.class) || JavaClassHelper.isImplementsInterface(contextPropertyNode.getType(), Map.class)) { return null; } if ((returnType != null) && (returnType.getClass().isArray())) { return null; } SimpleNumberCoercer coercer = getNumberCoercer(left.getExprEvaluator().getType(), contextPropertyNode.getType(), lookupable.getExpression()); listofValues.add(new InSetOfValuesContextProp(contextPropertyNode.getPropertyName(), contextPropertyNode.getGetter(), coercer)); } if (subNode instanceof ExprIdentNode) { ExprIdentNode identNodeInner = (ExprIdentNode) subNode; if (identNodeInner.getStreamId() == 0) { break; // for same event evals use the boolean expression, via count compare failing below } boolean isMustCoerce = false; Class numericCoercionType = JavaClassHelper.getBoxedType(lookupable.getReturnType()); if (identNodeInner.getExprEvaluator().getType() != lookupable.getReturnType()) { if (JavaClassHelper.isNumeric(lookupable.getReturnType())) { if (!JavaClassHelper.canCoerce(identNodeInner.getExprEvaluator().getType(), lookupable.getReturnType())) { throwConversionError(identNodeInner.getExprEvaluator().getType(), lookupable.getReturnType(), lookupable.getExpression()); } isMustCoerce = true; } else { break; // assumed not compatible } } FilterSpecParamInValue inValue; String streamName = identNodeInner.getResolvedStreamName(); if (arrayEventTypes != null && !arrayEventTypes.isEmpty() && arrayEventTypes.containsKey(streamName)) { Pair<Integer, String> indexAndProp = getStreamIndex(identNodeInner.getResolvedPropertyName()); inValue = new InSetOfValuesEventPropIndexed(identNodeInner.getResolvedStreamName(), indexAndProp.getFirst(), indexAndProp.getSecond(), isMustCoerce, numericCoercionType, statementName); } else { inValue = new InSetOfValuesEventProp(identNodeInner.getResolvedStreamName(), identNodeInner.getResolvedPropertyName(), isMustCoerce, numericCoercionType); } listofValues.add(inValue); } } // Fallback if not all values in the in-node can be resolved to properties or constants if (listofValues.size() == expectedNumberOfConstants) { return new FilterSpecParamIn(lookupable, op, listofValues); } return null; }