List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:Main.java
/** * Gets the size of the collection/iterator specified. * <p>//from w w w .ja v a 2 s .co m * This method can handles objects as follows * <ul> * <li>Collection - the collection size * <li>Map - the map size * <li>Array - the array size * <li>Iterator - the number of elements remaining in the iterator * <li>Enumeration - the number of elements remaining in the enumeration * </ul> * * @param object * the object to get the size of * @return the size of the specified collection * @throws IllegalArgumentException * thrown if object is not recognised or null * @since Commons Collections 3.1 */ public static int size(Object object) { int total = 0; if (object instanceof Map) { total = ((Map<?, ?>) object).size(); } else if (object instanceof Collection) { total = ((Collection<?>) object).size(); } else if (object instanceof Object[]) { total = ((Object[]) object).length; } else if (object instanceof Iterator) { Iterator<?> it = (Iterator<?>) object; while (it.hasNext()) { total++; it.next(); } } else if (object instanceof Enumeration) { Enumeration<?> it = (Enumeration<?>) object; while (it.hasMoreElements()) { total++; it.nextElement(); } } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { total = Array.getLength(object); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } return total; }
From source file:org.ajax4jsf.javascript.ScriptUtils.java
/** * Convert any Java Object to JavaScript representation ( as possible ). * @param obj/*from w ww . j a va2 s .co m*/ * @return */ public static String toScript(Object obj) { if (null == obj) { return "null"; } else if (obj instanceof ScriptString) { return ((ScriptString) obj).toScript(); } else if (obj.getClass().isArray()) { StringBuilder ret = new StringBuilder("["); boolean first = true; for (int i = 0; i < Array.getLength(obj); i++) { Object element = Array.get(obj, i); if (!first) { ret.append(','); } ret.append(toScript(element)); first = false; } return ret.append("] ").toString(); } else if (obj instanceof Collection) { // Collections put as JavaScript array. @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) obj; StringBuilder ret = new StringBuilder("["); boolean first = true; for (Iterator<Object> iter = collection.iterator(); iter.hasNext();) { Object element = iter.next(); if (!first) { ret.append(','); } ret.append(toScript(element)); first = false; } return ret.append("] ").toString(); } else if (obj instanceof Map) { // Maps put as JavaScript hash. @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) obj; StringBuilder ret = new StringBuilder("{"); boolean first = true; for (Map.Entry<Object, Object> entry : map.entrySet()) { if (!first) { ret.append(','); } addEncodedString(ret, entry.getKey()); ret.append(":"); ret.append(toScript(entry.getValue())); first = false; } return ret.append("} ").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. StringBuilder ret = new StringBuilder(); addEncodedString(ret, obj); return ret.toString(); } else if (obj instanceof Enum) { // all other put as encoded strings. StringBuilder ret = new StringBuilder(); addEncodedString(ret, obj); return ret.toString(); } else if (obj.getClass().getName().startsWith("java.sql.")) { StringBuilder ret = new StringBuilder("{"); boolean first = true; for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(obj)) { String key = propertyDescriptor.getName(); if ("class".equals(key)) { continue; } Object value = null; try { value = PropertyUtils.getProperty(obj, key); } catch (Exception e) { continue; } if (!first) { ret.append(','); } addEncodedString(ret, key); ret.append(":"); ret.append(toScript(value)); first = false; } return ret.append("} ").toString(); } // All other objects threaded as Java Beans. try { StringBuilder ret = new StringBuilder("{"); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj); boolean first = true; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String key = propertyDescriptor.getName(); if ("class".equals(key)) { continue; } if (!first) { ret.append(','); } addEncodedString(ret, key); ret.append(":"); ret.append(toScript(PropertyUtils.getProperty(obj, key))); first = false; } return ret.append("} ").toString(); } catch (Exception e) { throw new FacesException("Error in conversion Java Object to JavaScript", e); } }
From source file:com.wcs.base.util.ArrayUtils.java
/** * Concatenates two arrays into one. If arr1 is null or empty, returns arr2. * If arr2 is null or empty, returns arr1. May return null if both arrays are null, * or one is empty and the other null. <br> * The concatenated array has componentType which is compatible with both input arrays (or Object[]) * * @param arr1 input array//from w w w . ja va 2 s . c om * @param arr2 input array * * @return Object the concatenated array, elements of arr1 first */ public static Object concat(Object arr1, Object arr2) { int len1 = (arr1 == null) ? (-1) : Array.getLength(arr1); if (len1 <= 0) { return arr2; } int len2 = (arr2 == null) ? (-1) : Array.getLength(arr2); if (len2 <= 0) { return arr1; } Class commonComponentType = commonClass(arr1.getClass().getComponentType(), arr2.getClass().getComponentType()); Object newArray = Array.newInstance(commonComponentType, len1 + len2); System.arraycopy(arr1, 0, newArray, 0, len1); System.arraycopy(arr2, 0, newArray, len1, len2); return newArray; }
From source file:Main.java
/** * Builds a bracketed CSV list from the array * @param array an array of Objects/*from w w w.ja va 2s . co m*/ * @return string */ public static String arrayToString(Object array) { int len = Array.getLength(array); int last = len - 1; StringBuffer sb = new StringBuffer(2 * (len + 1)); sb.append('{'); for (int i = 0; i < len; i++) { sb.append(Array.get(array, i)); if (i != last) { sb.append(','); } } sb.append('}'); return sb.toString(); }
From source file:Main.java
public static JSONArray toJsonArray(Array array) { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < Array.getLength(array); i++) { Object elm = Array.get(array, i); if (elm instanceof Bundle) { jsonArray.put(toJsonObject((Bundle) elm)); } else if (elm instanceof List<?>) { jsonArray.put(toJsonArray((List<?>) elm)); } else if (elm instanceof Array) { jsonArray.put(toJsonArray((Array) elm)); } else {/*from w w w. ja va 2 s . c o m*/ jsonArray.put(elm.toString()); } } return jsonArray; }
From source file:org.jasig.cas.util.annotation.NotEmptyAnnotationBeanPostProcessor.java
protected void processField(final Field field, final Annotation annotation, final Object bean, final String beanName) throws IllegalAccessException { final Object obj = field.get(bean); if (obj == null) { throw new FatalBeanException(constructMessage(field, beanName)); }/*from ww w.j a va2 s .c o m*/ if (obj instanceof Collection) { final Collection<?> c = (Collection<?>) obj; if (c.isEmpty()) { throw new FatalBeanException(constructMessage(field, beanName)); } } if (obj.getClass().isArray()) { if (Array.getLength(obj) == 0) { throw new FatalBeanException(constructMessage(field, beanName)); } } if (obj instanceof Map) { final Map<?, ?> m = (Map<?, ?>) obj; if (m.isEmpty()) { throw new FatalBeanException(constructMessage(field, beanName)); } } }
From source file:com.opensymphony.webwork.util.ContainUtil.java
/** * Determine if <code>obj2</code> exists in <code>obj1</code>. *// w ww .j ava2s.co m * <table borer="1"> * <tr> * <td>Type Of obj1</td> * <td>Comparison type</td> * </tr> * <tr> * <td>null<td> * <td>always return false</td> * </tr> * <tr> * <td>Map</td> * <td>Map containsKey(obj2)</td> * </tr> * <tr> * <td>Collection</td> * <td>Collection contains(obj2)</td> * </tr> * <tr> * <td>Array</td> * <td>there's an array element (e) where e.equals(obj2)</td> * </tr> * <tr> * <td>Object</td> * <td>obj1.equals(obj2)</td> * </tr> * </table> * * * @param obj1 * @param obj2 * @return */ public static boolean contains(Object obj1, Object obj2) { if ((obj1 == null) || (obj2 == null)) { //log.debug("obj1 or obj2 are null."); return false; } if (obj1 instanceof Map) { if (((Map) obj1).containsKey(obj2)) { //log.debug("obj1 is a map and contains obj2"); return true; } } else if (obj1 instanceof Collection) { if (((Collection) obj1).contains(obj2)) { //log.debug("obj1 is a collection and contains obj2"); return true; } } else if (obj1.getClass().isArray()) { for (int i = 0; i < Array.getLength(obj1); i++) { Object value = null; value = Array.get(obj1, i); if (value.equals(obj2)) { //log.debug("obj1 is an array and contains obj2"); return true; } } } else if (obj1.equals(obj2)) { //log.debug("obj1 is an object and equals obj2"); return true; } //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2); return false; }
From source file:ArrayGrowTest.java
/** * This method grows an array by allocating a new array of the same type and * copying all elements./* ww w. ja v a 2 s . c o m*/ * * @param a * the array to grow. This can be an object array or a primitive type * array * @return a larger array that contains all elements of a. */ static Object goodArrayGrow(Object a) { Class cl = a.getClass(); if (!cl.isArray()) return null; Class componentType = cl.getComponentType(); int length = Array.getLength(a); int newLength = length * 11 / 10 + 10; Object newArray = Array.newInstance(componentType, newLength); System.arraycopy(a, 0, newArray, 0, length); return newArray; }
From source file:Main.java
public static JSONArray object2Json(Object data) throws JSONException { if (!data.getClass().isArray()) { throw new JSONException("Not a primitive data: " + data.getClass()); }/*w ww. j a v a 2 s .com*/ final int length = Array.getLength(data); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < length; ++i) { jsonArray.put(wrap(Array.get(data, i))); } return jsonArray; }
From source file:org.mstc.zmq.json.Encoder.java
public static String encode(Object o) throws IOException { StringWriter writer = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); JsonFactory factory = mapper.getFactory(); try (JsonGenerator g = factory.createGenerator(writer)) { g.writeStartObject();//from ww w .ja va 2s . c om for (Field f : o.getClass().getDeclaredFields()) { try { f.setAccessible(true); Object value = f.get(o); if (value != null) { if (f.getType().isAssignableFrom(List.class)) { String items = mapper.writeValueAsString(value); g.writeStringField(f.getName(), items); } else if (f.getType().isArray()) { if (f.getType().getComponentType().isAssignableFrom(byte.class)) { g.writeBinaryField(f.getName(), (byte[]) value); } else { int length = Array.getLength(value); g.writeFieldName(f.getName()); g.writeStartArray(); for (int i = 0; i < length; i++) { Object av = Array.get(value, i); if (av instanceof Double) { g.writeNumber(new BigDecimal((Double) av).toPlainString()); } else if (av instanceof Float) { g.writeNumber(new BigDecimal((Float) av).toPlainString()); } else if (av instanceof Integer) { g.writeNumber(new BigDecimal((Integer) av).toPlainString()); } else { g.writeObject(av); } /*if (av instanceof Double) g.writeNumber(new BigDecimal((Double) av)); else if (av instanceof Float) g.writeNumber(new BigDecimal((Float) av)); else if (av instanceof Integer) g.writeNumber((Integer) av);*/ } g.writeEndArray(); } } else { g.writeObjectField(f.getName(), value); } } } catch (IllegalAccessException e) { logger.warn("Could not get field: {}", f.getName(), e); } } g.writeEndObject(); } if (logger.isDebugEnabled()) logger.debug(writer.toString()); return writer.toString(); }