List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:org.apache.hadoop.hbase.util.JSONBean.java
private static void writeObject(final JsonGenerator jg, final boolean description, Object value) throws IOException { if (value == null) { jg.writeNull();// w w w .j a va 2 s .c om } else { Class<?> c = value.getClass(); if (c.isArray()) { jg.writeStartArray(); int len = Array.getLength(value); for (int j = 0; j < len; j++) { Object item = Array.get(value, j); writeObject(jg, description, item); } jg.writeEndArray(); } else if (value instanceof Number) { Number n = (Number) value; jg.writeNumber(n.toString()); } else if (value instanceof Boolean) { Boolean b = (Boolean) value; jg.writeBoolean(b); } else if (value instanceof CompositeData) { CompositeData cds = (CompositeData) value; CompositeType comp = cds.getCompositeType(); Set<String> keys = comp.keySet(); jg.writeStartObject(); for (String key : keys) { writeAttribute(jg, key, null, cds.get(key)); } jg.writeEndObject(); } else if (value instanceof TabularData) { TabularData tds = (TabularData) value; jg.writeStartArray(); for (Object entry : tds.values()) { writeObject(jg, description, entry); } jg.writeEndArray(); } else { jg.writeString(value.toString()); } } }
From source file:org.apache.struts2.interceptor.debugging.DebuggingInterceptor.java
/** * Recursive function to serialize objects to XML. Currently it will * serialize Collections, maps, Arrays, and JavaBeans. It maintains a stack * of objects serialized already in the current functioncall. This is used * to avoid looping (stack overflow) of circular linked objects. Struts and * XWork objects are ignored./*www .j a v a 2s.c om*/ * * @param bean The object you want serialized. * @param name The name of the object, used for element <name/> * @param writer The XML writer * @param stack List of objects we're serializing since the first calling * of this function (to prevent looping on circular references). */ protected void serializeIt(Object bean, String name, PrettyPrintWriter writer, List<Object> stack) { writer.flush(); // Check stack for this object if ((bean != null) && (stack.contains(bean))) { if (log.isInfoEnabled()) { log.info("Circular reference detected, not serializing object: " + name); } return; } else if (bean != null) { // Push object onto stack. // Don't push null objects ( handled below) stack.add(bean); } if (bean == null) { return; } String clsName = bean.getClass().getName(); writer.startNode(name); // It depends on the object and it's value what todo next: if (bean instanceof Collection) { Collection col = (Collection) bean; // Iterate through components, and call ourselves to process // elements for (Object aCol : col) { serializeIt(aCol, "value", writer, stack); } } else if (bean instanceof Map) { Map map = (Map) bean; // Loop through keys and call ourselves for (Object key : map.keySet()) { Object Objvalue = map.get(key); serializeIt(Objvalue, key.toString(), writer, stack); } } else if (bean.getClass().isArray()) { // It's an array, loop through it and keep calling ourselves for (int i = 0; i < Array.getLength(bean); i++) { serializeIt(Array.get(bean, i), "arrayitem", writer, stack); } } else { if (clsName.startsWith("java.lang")) { writer.setValue(bean.toString()); } else { // Not java.lang, so we can call ourselves with this object's // values try { BeanInfo info = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] props = info.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { String n = prop.getName(); Method m = prop.getReadMethod(); // Call ourselves with the result of the method // invocation if (m != null) { serializeIt(m.invoke(bean), n, writer, stack); } } } catch (Exception e) { log.error(e, e); } } } writer.endNode(); // Remove object from stack stack.remove(bean); }
From source file:com.segment.analytics.internal.Utils.java
/** * Wraps the given object if necessary. {@link JSONObject#wrap(Object)} is only available on API * 19+, so we've copied the implementation. Deviates from the original implementation in * that it always returns {@link JSONObject#NULL} instead of {@code null} in case of a failure, * and returns the {@link Object#toString} of any object that is of a custom (non-primitive or * non-collection/map) type.//from w w w .j a va 2 s .co m * * <p>If the object is null or , returns {@link JSONObject#NULL}. * If the object is a {@link JSONArray} or {@link JSONObject}, no wrapping is necessary. * If the object is {@link JSONObject#NULL}, no wrapping is necessary. * If the object is an array or {@link Collection}, returns an equivalent {@link JSONArray}. * If the object is a {@link Map}, returns an equivalent {@link JSONObject}. * If the object is a primitive wrapper type or {@link String}, returns the object. * Otherwise returns the result of {@link Object#toString}. * If wrapping fails, returns JSONObject.NULL. */ private static Object wrap(Object o) { if (o == null) { return JSONObject.NULL; } if (o instanceof JSONArray || o instanceof JSONObject) { return o; } if (o.equals(JSONObject.NULL)) { return o; } try { if (o instanceof Collection) { return new JSONArray((Collection) o); } else if (o.getClass().isArray()) { final int length = Array.getLength(o); JSONArray array = new JSONArray(); for (int i = 0; i < length; ++i) { array.put(wrap(Array.get(array, i))); } return array; } if (o instanceof Map) { //noinspection unchecked return toJsonObject((Map) o); } if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof String) { return o; } // Deviate from original implementation and return the String representation of the object // regardless of package. return o.toString(); } catch (Exception ignored) { } // Deviate from original and return JSONObject.NULL instead of null. return JSONObject.NULL; }
From source file:jef.tools.collection.CollectionUtil.java
/** * ?//from ww w . j ava 2 s . c om * @param obj * @return */ @SuppressWarnings("rawtypes") public static int length(Object obj) { if (obj.getClass().isArray()) { return Array.getLength(obj); } Assert.isTrue(obj instanceof Collection); return ((Collection) obj).size(); }
From source file:meizhi.meizhi.malin.utils.DestroyCleanUtil.java
/** * Hack TextLine// ww w .jav a2 s .c o m * http://stackoverflow.com/questions/30397356/android-memory-leak-on-textview-leakcanary-leak-can-be-ignored * https://github.com/square/leakcanary/blob/master/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidExcludedRefs.java * fix https://github.com/android/platform_frameworks_base/commit/b3a9bc038d3a218b1dbdf7b5668e3d6c12be5ee4 * <p> * blog: * http://snzang.leanote.com/post/c321f719cd02 */ public static void fixTextLineCacheLeak() { //if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) return; try { Field textLineCached; textLineCached = Class.forName("android.text.TextLine").getDeclaredField("sCached"); if (textLineCached == null) return; textLineCached.setAccessible(true); // Get reference to the TextLine sCached array. Object cached = textLineCached.get(null); if (cached == null) return; // Clear the array. for (int i = 0, size = Array.getLength(cached); i < size; i++) { Array.set(cached, i, null); } } catch (Throwable e) { e.printStackTrace(); } }
From source file:org.apache.hadoop.jmx.JMXJsonServlet.java
private void writeObject(JsonGenerator jg, Object value) throws IOException { if (value == null) { jg.writeNull();/*from w ww . ja va2s. com*/ } else { Class<?> c = value.getClass(); if (c.isArray()) { jg.writeStartArray(); int len = Array.getLength(value); for (int j = 0; j < len; j++) { Object item = Array.get(value, j); writeObject(jg, item); } jg.writeEndArray(); } else if (value instanceof Number) { Number n = (Number) value; jg.writeNumber(n.toString()); } else if (value instanceof Boolean) { Boolean b = (Boolean) value; jg.writeBoolean(b); } else if (value instanceof CompositeData) { CompositeData cds = (CompositeData) value; CompositeType comp = cds.getCompositeType(); Set<String> keys = comp.keySet(); jg.writeStartObject(); for (String key : keys) { writeAttribute(jg, key, cds.get(key)); } jg.writeEndObject(); } else if (value instanceof TabularData) { TabularData tds = (TabularData) value; jg.writeStartArray(); for (Object entry : tds.values()) { writeObject(jg, entry); } jg.writeEndArray(); } else { jg.writeString(value.toString()); } } }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitBareMethodMarshaller.java
public Message marshalResponse(Object returnObject, Object[] signatureArgs, OperationDescription operationDesc, Protocol protocol) throws WebServiceException { EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription(); EndpointDescription endpointDesc = ed.getEndpointDescription(); // We want to respond with the same protocol as the request, // It the protocol is null, then use the Protocol defined by the binding if (protocol == null) { protocol = Protocol.getProtocolForBinding(endpointDesc.getBindingType()); }// w w w. j av a2 s . c o m // Note all exceptions are caught and rethrown with a WebServiceException try { // Sample Document message // .. // <soapenv:body> // <m:return ... >...</m:param> // </soapenv:body> // // Important points. // 1) There is no operation element in the message // 2) The data blocks are located underneath the operation element. // 3) The name of the data blocks (m:param) are defined by the schema. // (SOAP indicates that the name of the element is not important, but // for document processing, we will assume that the name corresponds to // a schema root element) // 4) The type of the data block is defined by schema; thus in most cases // an xsi:type will not be present // Get the operation information ParameterDescription[] pds = operationDesc.getParameterDescriptions(); MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc); TreeSet<String> packages = marshalDesc.getPackages(); // Create the message MessageFactory mf = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class); Message m = mf.create(protocol); // Put the return object onto the message Class returnType = operationDesc.getResultActualType(); if (returnType != void.class) { AttachmentDescription attachmentDesc = operationDesc.getResultAttachmentDescription(); if (attachmentDesc != null) { if (attachmentDesc.getAttachmentType() == AttachmentType.SWA) { // Create an Attachment object with the signature value Attachment attachment = new Attachment(returnObject, returnType, attachmentDesc, operationDesc.getResultPartName()); m.addDataHandler(attachment.getDataHandler(), attachment.getContentID()); m.setDoingSWA(true); } else { throw ExceptionFactory.makeWebServiceException(Messages.getMessage("pdElementErr")); } } else { Element returnElement = null; QName returnQName = new QName(operationDesc.getResultTargetNamespace(), operationDesc.getResultName()); if (marshalDesc.getAnnotationDesc(returnType).hasXmlRootElement()) { returnElement = new Element(returnObject, returnQName); } else { /* when a schema defines a SimpleType with xsd list jaxws tooling generates art-effects with array rather than a java.util.List * However the ObjectFactory definition uses a List and thus marshalling fails. Lets convert the Arrays to List. */ if (operationDesc.isListType()) { List list = new ArrayList(); if (returnType.isArray()) { for (int count = 0; count < Array.getLength(returnObject); count++) { Object obj = Array.get(returnObject, count); list.add(obj); } returnElement = new Element(list, returnQName, List.class); } } else { returnElement = new Element(returnObject, returnQName, returnType); } } MethodMarshallerUtils.toMessage(returnElement, returnType, operationDesc.isListType(), marshalDesc, m, null, // always marshal using "by element" mode operationDesc.isResultHeader()); } } // Convert the holder objects into a list of JAXB objects for marshalling List<PDElement> pvList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArgs, false, // output false, false); // Put values onto the message MethodMarshallerUtils.toMessage(pvList, m, packages, null); // Enable SWA for nested SwaRef attachments if (operationDesc.hasResponseSwaRefAttachments()) { m.setDoingSWA(true); } return m; } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } }
From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java
private XYDataset createXYDataset(int numberOfLines, String[] lineNames, double lx[][], double ly[][], int numberOfDotGroup, String[] dotGroupNames, double dx[][], double dy[][]) { XYSeriesCollection dataset = new XYSeriesCollection(); for (int j = 0; j < numberOfLines; j++) { XYSeries serie = new XYSeries(lineNames[j]); int len = Array.getLength(lx[j]); for (int i = 0; i < len; i++) serie.add(lx[j][i], ly[j][i]); dataset.addSeries(serie);/*from w ww . jav a2 s .c o m*/ } for (int j = 0; j < numberOfDotGroup; j++) { XYSeries serie = new XYSeries(dotGroupNames[j]); int len = Array.getLength(dx[j]); for (int i = 0; i < len; i++) serie.add(dx[j][i], dy[j][i]); dataset.addSeries(serie); } return dataset; }
From source file:com.alta189.cyborg.api.util.config.ini.IniConfiguration.java
/** * Returns the String representation of a configuration value for writing to the file * @param value/* ww w . j av a 2s . c o m*/ * @return */ public String toStringValue(Object value) { if (value == null) { return "null"; } if (value.getClass().isArray()) { List<Object> toList = new ArrayList<Object>(); final int length = Array.getLength(value); for (int i = 0; i < length; ++i) { toList.add(Array.get(value, i)); } value = toList; } if (value instanceof Collection) { StringBuilder builder = new StringBuilder(); for (Object obj : (Collection<?>) value) { if (builder.length() > 0) { builder.append(", "); } builder.append(obj.toString()); } return builder.toString(); } else { String strValue = value.toString(); if (strValue.contains(",")) { strValue = '"' + strValue + '"'; } return strValue; } }
From source file:com.gh.bmd.jrt.android.v4.core.LoaderInvocation.java
private static int recursiveHashCode(@Nullable final Object object) { if (object == null) { return 0; }//www .ja v a 2s .c o m if (object.getClass().isArray()) { int hashCode = 0; final int length = Array.getLength(object); for (int i = 0; i < length; i++) { hashCode = 31 * hashCode + recursiveHashCode(Array.get(object, i)); } return hashCode; } return object.hashCode(); }