List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:com.partypoker.poker.engagement.utils.EngagementBundleToJSON.java
/** * Recursive function to write a value to JSON. * @param json the JSON serializer./*ww w .j a va 2s . com*/ * @param value the value to write in JSON. */ private static void convert(JSONStringer json, Object value) throws JSONException { /* Handle null */ if (value == null) json.value(null); /* The function is recursive if it encounters a bundle */ else if (value instanceof Bundle) { /* Cast bundle */ Bundle bundle = (Bundle) value; /* Open object */ json.object(); /* Traverse bundle */ for (String key : bundle.keySet()) { /* Write key */ json.key(key); /* Recursive call to write the value */ convert(json, bundle.get(key)); } /* End object */ json.endObject(); } /* Handle array, write it as a JSON array */ else if (value.getClass().isArray()) { /* Open array */ json.array(); /* Recursive call on each value */ int length = Array.getLength(value); for (int i = 0; i < length; i++) convert(json, Array.get(value, i)); /* Close array */ json.endArray(); } /* Handle ArrayList, write it as a JSON array */ else if (value instanceof ArrayList<?>) { /* Open array */ json.array(); /* Recursive call on each value */ ArrayList<?> arrayList = (ArrayList<?>) value; for (Object val : arrayList) convert(json, val); /* Close array */ json.endArray(); } /* Format throwable values with the stack trace */ else if (value instanceof Throwable) { Throwable t = (Throwable) value; StringWriter text = new StringWriter(); t.printStackTrace(new PrintWriter(text)); json.value(text.toString()); } /* Other values are handled directly by JSONStringer (numerical, boolean and String) */ else json.value(value); }
From source file:ArrayUtils.java
/** * Inserts an element into the array--for primitive types * //from www . j a va 2 s . c om * @param anArray * The array to insert into * @param anElement * The element to insert * @param anIndex * The index for the new element * @return The new array with all elements of <code>anArray</code>, but with * <code>anElement</code> inserted at index <code>anIndex</code> */ public static Object addP(Object anArray, Object anElement, int anIndex) { Object ret; int length; if (anArray == null) { if (anIndex != 0) throw new ArrayIndexOutOfBoundsException("Cannot set " + anIndex + " element in a null array"); ret = Array.newInstance(anElement.getClass(), 1); Array.set(ret, 0, anElement); return ret; } else { length = Array.getLength(anArray); ret = Array.newInstance(anArray.getClass().getComponentType(), length + 1); } System.arraycopy(anArray, 0, ret, 0, anIndex); put(ret, anElement, anIndex); System.arraycopy(anArray, anIndex, ret, anIndex + 1, length - anIndex); return ret; }
From source file:mil.jpeojtrs.sca.util.PrimitiveArrayUtils.java
public static double[] convertToDoubleArray(final Object array) { if (array == null) { return null; }//from w w w . ja v a 2 s. c o m if (array instanceof double[]) { return (double[]) array; } if (array instanceof Double[]) { return ArrayUtils.toPrimitive((Double[]) array); } final double[] newArray = new double[Array.getLength(array)]; for (int i = 0; i < newArray.length; i++) { final Number val = (Number) Array.get(array, i); newArray[i] = val.doubleValue(); } return newArray; }
From source file:de.tuberlin.uebb.jbop.optimizer.array.LocalArrayLengthInliner.java
@Override protected boolean handleValues(final InsnList original, final Map<Integer, Object> knownArrays, final AbstractInsnNode currentNode) { if (!NodeHelper.isArrayLength(currentNode)) { return false; }//from w w w. j av a 2 s. co m AbstractInsnNode previous = NodeHelper.getPrevious(currentNode); final List<AbstractInsnNode> toBeRemoved = new ArrayList<>(); int index2 = 0; while ((previous != null) && !NodeHelper.isAload(previous)) { if (NodeHelper.isAAload(previous)) { index2 += 1; } toBeRemoved.add(previous); previous = NodeHelper.getPrevious(previous); } final int index; if ((previous != null) && NodeHelper.isAload(previous)) { toBeRemoved.add(previous); index = ((VarInsnNode) previous).var; } else { return false; } final Object array = knownArrays.get(Integer.valueOf(index)); if ((array == null)) { return false; } Object array2 = array; for (int i = 0; i < index2; ++i) { array2 = Array.get(array2, i); } final int arrayLength = Array.getLength(array2); original.insertBefore(currentNode, NodeHelper.getInsnNodeFor(arrayLength)); for (final AbstractInsnNode remove : toBeRemoved) { original.remove(remove); } original.remove(currentNode); return true; }
From source file:de.micromata.genome.util.matcher.cls.AnnotationAttributeClassMatcher.java
/** * Contains value.//from w w w . ja v a2 s. c o m * * @param array the array * @return true, if successful */ protected boolean containsValue(Object array) { int len = Array.getLength(array); for (int i = 0; i < len; ++i) { Object val = Array.get(array, i); if (compareSimpleType(val) == true) { return true; } } return false; }
From source file:ddf.catalog.validation.impl.validator.SizeValidator.java
/** * {@inheritDoc}//w w w . j av a 2s . c o m * <p> * Validates only the values of {@code attribute} that are {@link CharSequence}s, * {@link Collection}s, {@link Map}s, or arrays. */ @Override public Optional<AttributeValidationReport> validate(final Attribute attribute) { Preconditions.checkArgument(attribute != null, "The attribute cannot be null."); final String name = attribute.getName(); for (final Serializable value : attribute.getValues()) { int size; if (value instanceof CharSequence) { size = ((CharSequence) value).length(); } else if (value instanceof Collection) { size = ((Collection) value).size(); } else if (value instanceof Map) { size = ((Map) value).size(); } else if (value != null && value.getClass().isArray()) { size = Array.getLength(value); } else { continue; } if (!checkSize(size)) { final String violationMessage = String.format("%s size must be between %d and %d", name, min, max); final AttributeValidationReportImpl report = new AttributeValidationReportImpl(); report.addViolation( new ValidationViolationImpl(Collections.singleton(name), violationMessage, Severity.ERROR)); return Optional.of(report); } } return Optional.empty(); }
From source file:com.xpfriend.fixture.cast.temp.ObjectOperatorBase.java
private Object toArrayInternal(Class<?> componentType, String textValue) { String[] textValues = textValue.split("\\|"); if (String.class.equals(componentType)) { return textValues; }//from w w w . ja va 2s . com Object values = Array.newInstance(componentType, textValues.length); for (int i = 0; i < Array.getLength(values); i++) { Array.set(values, i, TypeConverter.changeType(textValues[i], componentType)); } return values; }
From source file:com.mtgi.analytics.aop.BehaviorTrackingAdvice.java
protected static final String toStringArray(Object array) { StringBuffer ret = new StringBuffer("["); int len = Array.getLength(array); int maxLen = Math.min(len, 100); for (int i = 0; i < maxLen; ++i) { if (i > 0) ret.append(", "); ret.append(String.valueOf(Array.get(array, i))); }/*w w w. j a v a 2 s. c o m*/ if (maxLen < len) ret.append(", ... (").append(len - maxLen).append(" more)"); ret.append("]"); return ret.toString(); }
From source file:org.apache.click.util.RequestTypeConverter.java
/** * Return the converted value for the given value object and target type. * * @param value the value object to convert * @param toType the target class type to convert the value to * @return a converted value into the specified type *//*from w w w .ja va2s. co m*/ protected Object convertValue(Object value, Class<?> toType) { Object result = null; if (value != null) { // If array -> array then convert components of array individually if (value.getClass().isArray() && toType.isArray()) { Class<?> componentType = toType.getComponentType(); result = Array.newInstance(componentType, Array.getLength(value)); for (int i = 0, icount = Array.getLength(value); i < icount; i++) { Array.set(result, i, convertValue(Array.get(value, i), componentType)); } } else { if ((toType == Integer.class) || (toType == Integer.TYPE)) { result = Integer.valueOf((int) OgnlOps.longValue(value)); } else if ((toType == Double.class) || (toType == Double.TYPE)) { result = new Double(OgnlOps.doubleValue(value)); } else if ((toType == Boolean.class) || (toType == Boolean.TYPE)) { result = Boolean.valueOf(value.toString()); } else if ((toType == Byte.class) || (toType == Byte.TYPE)) { result = Byte.valueOf((byte) OgnlOps.longValue(value)); } else if ((toType == Character.class) || (toType == Character.TYPE)) { result = Character.valueOf((char) OgnlOps.longValue(value)); } else if ((toType == Short.class) || (toType == Short.TYPE)) { result = Short.valueOf((short) OgnlOps.longValue(value)); } else if ((toType == Long.class) || (toType == Long.TYPE)) { result = Long.valueOf(OgnlOps.longValue(value)); } else if ((toType == Float.class) || (toType == Float.TYPE)) { result = new Float(OgnlOps.doubleValue(value)); } else if (toType == BigInteger.class) { result = OgnlOps.bigIntValue(value); } else if (toType == BigDecimal.class) { result = bigDecValue(value); } else if (toType == String.class) { result = OgnlOps.stringValue(value); } else if (toType == java.util.Date.class) { long time = getTimeFromDateString(value.toString()); if (time > Long.MIN_VALUE) { result = new java.util.Date(time); } } else if (toType == java.sql.Date.class) { long time = getTimeFromDateString(value.toString()); if (time > Long.MIN_VALUE) { result = new java.sql.Date(time); } } else if (toType == java.sql.Time.class) { long time = getTimeFromDateString(value.toString()); if (time > Long.MIN_VALUE) { result = new java.sql.Time(time); } } else if (toType == java.sql.Timestamp.class) { long time = getTimeFromDateString(value.toString()); if (time > Long.MIN_VALUE) { result = new java.sql.Timestamp(time); } } } } else { if (toType.isPrimitive()) { result = OgnlRuntime.getPrimitiveDefaultValue(toType); } } return result; }
From source file:org.apache.catalina.mbeans.MBeanDumper.java
/** * The following code to dump MBeans has been copied from JMXProxyServlet. * *//*from www.j a v a 2 s . co m*/ public static String dumpBeans(MBeanServer mbeanServer, Set<ObjectName> names) { StringBuilder buf = new StringBuilder(); Iterator<ObjectName> it = names.iterator(); while (it.hasNext()) { ObjectName oname = it.next(); buf.append("Name: "); buf.append(oname.toString()); buf.append(CRLF); try { MBeanInfo minfo = mbeanServer.getMBeanInfo(oname); // can't be null - I think String code = minfo.getClassName(); if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) { code = (String) mbeanServer.getAttribute(oname, "modelerType"); } buf.append("modelerType: "); buf.append(code); buf.append(CRLF); MBeanAttributeInfo attrs[] = minfo.getAttributes(); Object value = null; for (int i = 0; i < attrs.length; i++) { if (!attrs[i].isReadable()) continue; String attName = attrs[i].getName(); if ("modelerType".equals(attName)) continue; if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) { continue; } try { value = mbeanServer.getAttribute(oname, attName); } catch (JMRuntimeException rme) { Throwable cause = rme.getCause(); if (cause instanceof UnsupportedOperationException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else if (cause instanceof NullPointerException) { if (log.isDebugEnabled()) { log.debug("Error getting attribute " + oname + " " + attName, rme); } } else { log.error("Error getting attribute " + oname + " " + attName, rme); } continue; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Error getting attribute " + oname + " " + attName, t); continue; } if (value == null) continue; String valueString; try { Class<?> c = value.getClass(); if (c.isArray()) { int len = Array.getLength(value); StringBuilder sb = new StringBuilder( "Array[" + c.getComponentType().getName() + "] of length " + len); if (len > 0) { sb.append(CRLF); } for (int j = 0; j < len; j++) { sb.append("\t"); Object item = Array.get(value, j); if (item == null) { sb.append("NULL VALUE"); } else { try { sb.append(escape(item.toString())); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); sb.append("NON-STRINGABLE VALUE"); } } if (j < len - 1) { sb.append(CRLF); } } valueString = sb.toString(); } else { valueString = escape(value.toString()); } buf.append(attName); buf.append(": "); buf.append(valueString); buf.append(CRLF); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } buf.append(CRLF); } return buf.toString(); }