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.heliosapm.opentsdb.client.jvmjmx.custom.aggregation.AggregateFunction.java
/** * Computes and returns the aggregate for the named aggregator and object of nput items. * The object is introspected to determine if it is:<ul> * <li>Null</li>//w ww .j av a2s. co m * <li>{@link java.util.Map}</li> * <li>{@link java.util.Collection}</li> * <li>An array</li> * </ul>. * If it is none of the above, a runtime exception is thrown. * If it is a map or an array, it is converted to a list for aggregate computation. * @param name The name of the aggregator function * @param item The object of items to aggregate * @return the aggregate value * TODO: Do we need to support multi dimmensional arrays ? */ @SuppressWarnings("unchecked") public static Object aggregate(CharSequence name, Object item) { final List<Object> items; final AggregateFunction function = AggregateFunction.forName(name); if (item == null) { items = Collections.EMPTY_LIST; } else if (item instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) item; items = new ArrayList<Object>(map.keySet()); } else if (item instanceof Collection) { items = new ArrayList<Object>((Collection<Object>) item); } else if (item.getClass().isArray()) { int length = Array.getLength(item); items = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { items.add(i, Array.get(item, i)); } } else { throw new IllegalArgumentException("Aggregate object of type [" + item.getClass().getName() + "] was not a Map, Collection or Array", new Throwable()); } return function.aggregate(items); }
From source file:ArrayUtils.java
/** * Moves an element in a primitive array from one index to another * //from w ww. j a v a 2 s . c o m * @param anArray * The array to move an element within * @param from * The index of the element to move * @param to * The index to move the element to * @return The original array */ public static Object moveP(Object anArray, int from, int to) { if (anArray instanceof Object[]) return move((Object[]) anArray, from, to); final Object element = Array.get(anArray, from); for (; from < to; from++) Array.set(anArray, from, Array.get(anArray, from + 1)); for (; from > to; from--) Array.set(anArray, from, Array.get(anArray, from - 1)); Array.set(anArray, to, element); return anArray; }
From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java
/** * Converts the supplied object to the specified * type. Throws a runtime exception if the conversion is * not possible.//from ww w . ja v a2 s . co m * @param object to convert * @param toType destination class * @return converted object */ public Object convert(Object object, final Class toType) { if (object == null) { return toType.isPrimitive() ? convertNullToPrimitive(toType) : null; } if (toType == Object.class) { if (object instanceof NodeSet) { return convert(((NodeSet) object).getValues(), toType); } if (object instanceof Pointer) { return convert(((Pointer) object).getValue(), toType); } return object; } final Class useType = TypeUtils.wrapPrimitive(toType); Class fromType = object.getClass(); if (useType.isAssignableFrom(fromType)) { return object; } if (fromType.isArray()) { int length = Array.getLength(object); if (useType.isArray()) { Class cType = useType.getComponentType(); Object array = Array.newInstance(cType, length); for (int i = 0; i < length; i++) { Object value = Array.get(object, i); Array.set(array, i, convert(value, cType)); } return array; } if (Collection.class.isAssignableFrom(useType)) { Collection collection = allocateCollection(useType); for (int i = 0; i < length; i++) { collection.add(Array.get(object, i)); } return unmodifiableCollection(collection); } if (length > 0) { Object value = Array.get(object, 0); return convert(value, useType); } return convert("", useType); } if (object instanceof Collection) { int length = ((Collection) object).size(); if (useType.isArray()) { Class cType = useType.getComponentType(); Object array = Array.newInstance(cType, length); Iterator it = ((Collection) object).iterator(); for (int i = 0; i < length; i++) { Object value = it.next(); Array.set(array, i, convert(value, cType)); } return array; } if (Collection.class.isAssignableFrom(useType)) { Collection collection = allocateCollection(useType); collection.addAll((Collection) object); return unmodifiableCollection(collection); } if (length > 0) { Object value; if (object instanceof List) { value = ((List) object).get(0); } else { Iterator it = ((Collection) object).iterator(); value = it.next(); } return convert(value, useType); } return convert("", useType); } if (object instanceof NodeSet) { return convert(((NodeSet) object).getValues(), useType); } if (object instanceof Pointer) { return convert(((Pointer) object).getValue(), useType); } if (useType == String.class) { return object.toString(); } if (object instanceof Boolean) { if (Number.class.isAssignableFrom(useType)) { return allocateNumber(useType, ((Boolean) object).booleanValue() ? 1 : 0); } if ("java.util.concurrent.atomic.AtomicBoolean".equals(useType.getName())) { try { return useType.getConstructor(new Class[] { boolean.class }) .newInstance(new Object[] { object }); } catch (Exception e) { throw new JXPathTypeConversionException(useType.getName(), e); } } } if (object instanceof Number) { double value = ((Number) object).doubleValue(); if (useType == Boolean.class) { return value == 0.0 ? Boolean.FALSE : Boolean.TRUE; } if (Number.class.isAssignableFrom(useType)) { return allocateNumber(useType, value); } } if (object instanceof String) { Object value = convertStringToPrimitive(object, useType); if (value != null || "".equals(object)) { return value; } } Converter converter = ConvertUtils.lookup(useType); if (converter != null) { return converter.convert(useType, object); } throw new JXPathTypeConversionException("Cannot convert " + object.getClass() + " to " + useType); }
From source file:com.krawler.br.exp.Variable.java
private Object getIndexedElement(Object container, int index) throws ProcessException { if (indices != null && indices.containsKey(index)) { Iterator<Expression> itr = indices.get(index).iterator(); while (container != null && itr.hasNext()) { int idx = ((Number) itr.next().getValue()).intValue(); if (container instanceof JSONArray) { container = ((JSONArray) container).opt(idx); } else if (container instanceof java.util.List) { container = ((java.util.List) container).get(idx); } else if (container.getClass().isArray()) { container = Array.get(container, idx); } else container = null;//from w w w . j av a 2 s . c o m } } return container; }
From source file:com.l2jfree.util.Introspection.java
private static void deepToString(Object obj, StringBuilder dest, Set<Object> dejaVu) throws SecurityException, NoSuchMethodException { if (obj == null) { dest.append("null"); return;/* w ww . j a v a 2 s. co m*/ } if (obj.getClass().isArray()) { final int length = Array.getLength(obj); if (length == 0) { dest.append("[]"); return; } if (dejaVu == null) dejaVu = new HashSet<Object>(); dejaVu.add(obj); dest.append('['); for (int i = 0; i < length; i++) { if (i != 0) dest.append(", "); final Object element = Array.get(obj, i); if (dejaVu.contains(element)) dest.append("[...]"); else deepToString(element, dest, dejaVu); } dest.append(']'); dejaVu.remove(obj); } else { if (obj.getClass().getMethod("toString").getDeclaringClass() == Object.class) dest.append(Introspection.toString(obj)); else dest.append(obj.toString()); } }
From source file:org.bbreak.excella.reports.util.ReportsUtil.java
/** * ?????????????<BR>// ww w. ja v a 2 s . c o m * * <pre> * ? * ??:??? * * $R[]:? * $C: * $:??? * ??????????:????$:??? * * ($BR[]?$BC[])?.???? * ????? * ??:???.??:???.??:??? * * $BR[]:.$R[]: * $BR[]:.?? * </pre> * * @param info * @param propertyNameString ? * @param parsers ? * @return ???? */ public static List<Object> getParamValues(ParamInfo info, String propertyNameString, List<ReportsTagParser<?>> parsers) { String[] levels = propertyNameString.split("\\."); List<Object> paramValues = new ArrayList<Object>(); ParamInfo[] paramInfos = new ParamInfo[] { info }; for (String level : levels) { String tagName = null; String propertyName = null; if (level.indexOf(":") != -1) { // ? String[] values = level.split(":"); tagName = values[0]; propertyName = values[1]; } else { // ?????? tagName = SingleParamParser.DEFAULT_TAG; propertyName = level; } List<SingleParamParser> singleParsers = new ArrayList<SingleParamParser>(); for (ReportsTagParser<?> reportsParser : parsers) { if (reportsParser instanceof SingleParamParser) { singleParsers.add((SingleParamParser) reportsParser); } } // ???? ReportsTagParser<?> targetParser = null; for (ReportsTagParser<?> tagParser : parsers) { if (tagParser.getTag().equals(tagName)) { targetParser = tagParser; } } if (targetParser == null) { // ?? break; } // ?? Object object = null; for (ParamInfo paramInfo : paramInfos) { object = targetParser.getParamData(paramInfo, propertyName); if (object != null) { break; } } if (object != null) { if (object instanceof ParamInfo[]) { // $BR[],$BC[] List<ParamInfo> newParamInfos = new ArrayList<ParamInfo>(); for (ParamInfo paramInfo : paramInfos) { ParamInfo[] params = (ParamInfo[]) targetParser.getParamData(paramInfo, propertyName); if (params != null) { newParamInfos.addAll(Arrays.asList(params)); } } paramInfos = newParamInfos.toArray(new ParamInfo[newParamInfos.size()]); } else if (object.getClass().isArray()) { if (Array.getLength(object) == 0) { continue; } if (Array.get(object, 0) instanceof String || Array.get(object, 0) instanceof Number || Array.get(object, 0) instanceof Date || Array.get(object, 0) instanceof Boolean) { // $R[],$C[] for (ParamInfo paramInfo : paramInfos) { Object arrayObj = targetParser.getParamData(paramInfo, propertyName); if (arrayObj != null) { for (int i = 0; i < Array.getLength(arrayObj); i++) { paramValues.add(Array.get(arrayObj, i)); } } } } else { // $BR[],$BC[] List<ParamInfo> newParamInfos = new ArrayList<ParamInfo>(); for (ParamInfo paramInfo : paramInfos) { Object[] params = (Object[]) targetParser.getParamData(paramInfo, propertyName); // POJOParamInfo??? for (Object obj : params) { if (obj instanceof ParamInfo) { newParamInfos.add((ParamInfo) obj); continue; } ParamInfo childParamInfo = new ParamInfo(); Map<String, Object> map = null; try { map = PropertyUtils.describe(obj); } catch (Exception e) { throw new RuntimeException( "????????", e); } for (Map.Entry<String, Object> entry : map.entrySet()) { for (ReportsTagParser<?> parser : singleParsers) { childParamInfo.addParam(parser.getTag(), entry.getKey(), entry.getValue()); } } newParamInfos.add(childParamInfo); } } paramInfos = newParamInfos.toArray(new ParamInfo[newParamInfos.size()]); } } else if (object instanceof Collection<?>) { for (ParamInfo paramInfo : paramInfos) { Collection<?> collection = (Collection<?>) targetParser.getParamData(paramInfo, propertyName); if (collection != null) { paramValues.addAll(collection); } } } else { // $,$I for (ParamInfo paramInfo : paramInfos) { Object value = targetParser.getParamData(paramInfo, propertyName); if (value != null) { paramValues.add(value); } } } } } return paramValues; }
From source file:org.jbpm.formModeler.core.processing.fieldHandlers.CreateDynamicObjectFieldFormatter.java
protected void previewItemInPosition(Form parentForm, String currentNamespace, int position, Field field, Object value) {/*from w w w. j a v a 2 s.c o m*/ if (value != null) { if (value.getClass().isArray()) { CreateDynamicObjectFieldHandler fieldHandler = (CreateDynamicObjectFieldHandler) getFieldHandlersManager() .getHandler(field.getFieldType()); Form formToPreview = fieldHandler.getPreviewDataForm(field, currentNamespace); Map valueToPreview = (Map) Array.get(value, position); if (formToPreview != null) { setAttribute("valueToPreview", valueToPreview); setAttribute("form", formToPreview); setAttribute("uid", fieldUID); setAttribute("index", position); setAttribute("parentFormId", parentForm.getId()); setAttribute("namespace", fieldNS); setAttribute("parentNamespace", currentNamespace); setAttribute("field", field.getFieldName()); // Override the field's own disabled and readonly values with the ones coming from a parent formatter // that contains it if they're set to true. if (isReadonly) setAttribute("readonly", isReadonly); renderFragment("previewItem"); } else { renderFragment("noShowDataForm"); } } } }
From source file:com.jskaleel.xml.JSONArray.java
/** * Construct a JSONArray from an array// w w w.j a va 2s . c o m * * @throws JSONException * If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } }
From source file:com.examples.with.different.packagename.testcarver.AbstractConverter.java
/** * Return the first element from an Array (or Collection) * or the value unchanged if not an Array (or Collection). * * N.B. This needs to be overriden for array/Collection converters. * * @param value The value to convert/* w w w. j ava 2 s . co m*/ * @return The first element in an Array (or Collection) * or the value unchanged if not an Array (or Collection) */ protected Object convertArray(Object value) { if (value == null) { return null; } if (value.getClass().isArray()) { if (Array.getLength(value) > 0) { return Array.get(value, 0); } else { return null; } } if (value instanceof Collection) { Collection collection = (Collection) value; if (collection.size() > 0) { return collection.iterator().next(); } else { return null; } } return value; }
From source file:org.ajax4jsf.builder.mojo.CompileMojo.java
/** * Convert any Java Object to JavaScript representation ( as possible ). * /*from w ww . j a v a 2 s. co m*/ * @param obj * @return * @throws MojoExecutionException */ public String toLog(Object obj) throws MojoExecutionException { if (null == obj) { return "null"; } else if (obj.getClass().isArray()) { StringBuffer ret = new StringBuffer("["); boolean first = true; for (int i = 0; i < Array.getLength(obj); i++) { Object element = Array.get(obj, i); if (!first) { ret.append(','); } ret.append(toLog(element)); first = false; } return ret.append("]\n").toString(); } else if (obj instanceof Collection) { // Collections put as JavaScript array. Collection collection = (Collection) obj; StringBuffer ret = new StringBuffer("["); boolean first = true; for (Iterator iter = collection.iterator(); iter.hasNext();) { Object element = iter.next(); if (!first) { ret.append(','); } ret.append(toLog(element)); first = false; } return ret.append("]\n").toString(); } else if (obj instanceof Map) { // Maps put as JavaScript hash. Map map = (Map) obj; StringBuffer ret = new StringBuffer("{"); boolean first = true; for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { Object key = (Object) iter.next(); if (!first) { ret.append(','); } ret.append(key); ret.append(":"); ret.append(toLog(map.get(key))); first = false; } return ret.append("}\n").toString(); } else if (obj instanceof Number || obj instanceof Boolean) { // numbers and boolean put as-is, without conversion return obj.toString(); } else if (obj instanceof String) { // all other put as encoded strings. StringBuffer ret = new StringBuffer(); addEncodedString(ret, obj); return ret.append("\n").toString(); } // All other objects threaded as Java Beans. try { StringBuffer ret = new StringBuffer("{"); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj); boolean first = true; for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; String key = propertyDescriptor.getName(); if ("class".equals(key) || propertyDescriptor.getReadMethod() == null) { continue; } if (!first) { ret.append(",\n\t"); } addEncodedString(ret, key); ret.append(":"); try { ret.append(String.valueOf(PropertyUtils.getProperty(obj, key))); } catch (InvocationTargetException e) { ret.append("Not ACCESIBLE"); } // ret.append(toLog(PropertyUtils.getProperty(obj, key))); first = false; } return ret.append("}\n").toString(); } catch (Exception e) { throw new MojoExecutionException("Error in conversion Java Object to String", e); } }