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.apache.myfaces.el.PropertyResolverImpl.java
public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException { try {// ww w .j ava 2s.c o m if (base == null) { log.debug("index : " + index + " not retrievable cause base is null."); return null; } try { if (base.getClass().isArray()) { return Array.get(base, index); } if (base instanceof List) { return ((List) base).get(index); } } catch (IndexOutOfBoundsException e) { if (log.isDebugEnabled()) log.debug("IndexOutOfBoundException while getting property; base with class: " + base.getClass().getName() + ", index : " + index, e); // Note: ArrayIndexOutOfBoundsException also here return null; } throw new ReferenceSyntaxException( "Must be array or List. Bean with class: " + base.getClass().getName() + ", index " + index); } catch (RuntimeException e) { if (log.isDebugEnabled()) log.debug("Exception while getting property; base with class: " + base.getClass().getName() + ", index : " + index, e); throw new EvaluationException("Exception getting value for index " + index + " of bean " + base != null ? base.getClass().getName() : "NULL", e); } }
From source file:Main.java
/** * convert value to given type.//w w w .j a v a2s . com * null safe. * * @param value value for convert * @param type will converted type * @return value while converted */ public static Object convertCompatibleType(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return Short.valueOf(string); } else if (type == Integer.class || type == int.class) { return Integer.valueOf(string); } else if (type == Long.class || type == long.class) { return Long.valueOf(string); } else if (type == Double.class || type == double.class) { return Double.valueOf(string); } else if (type == Float.class || type == float.class) { return Float.valueOf(string); } else if (type == Byte.class || type == byte.class) { return Byte.valueOf(string); } else if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { return forName((String) value); } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { e.printStackTrace(); } } else if (type == List.class) { return new ArrayList<>(collection); } else if (type == Set.class) { return new HashSet<>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<>(); } } else if (type == Set.class) { collection = new HashSet<>(); } else { collection = new ArrayList<>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
From source file:org.kie.remote.jaxb.gen.util.JaxbUnknownAdapter.java
private Object recursiveMarshal(Object o, Map<Object, Object> seenObjectsMap) { if (o == null) { return o; }//w w w . j a v a 2s.c o m if (seenObjectsMap.put(o, PRESENT) != null) { throw new UnsupportedOperationException("Serialization of recursive data structures is not supported!"); } try { if (o instanceof List) { List list = (List) o; List<Object> serializedList = convertCollectionToSerializedList(list, seenObjectsMap); org.kie.remote.jaxb.gen.List listWrapper = new org.kie.remote.jaxb.gen.List(); listWrapper.getElements().addAll(serializedList); listWrapper.setType(org.kie.remote.jaxb.gen.JaxbWrapperType.LIST); return listWrapper; } else if (o instanceof Set) { Set set = (Set) o; List<Object> serializedList = convertCollectionToSerializedList(set, seenObjectsMap); org.kie.remote.jaxb.gen.List listWrapper = new org.kie.remote.jaxb.gen.List(); listWrapper.getElements().addAll(serializedList); listWrapper.setType(org.kie.remote.jaxb.gen.JaxbWrapperType.SET); return listWrapper; } else if (o instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) o; List<JaxbStringObjectPair> pairList = new ArrayList<JaxbStringObjectPair>(map.size()); if (map == null || map.isEmpty()) { pairList = Collections.EMPTY_LIST; } for (Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); if (key != null && !(key instanceof String)) { throw new UnsupportedOperationException( "Only String keys for Map structures are supported [key was a " + key.getClass().getName() + "]"); } // There's already a @XmlJavaTypeAdapter(JaxbUnknownAdapter.class) anno on the JaxbStringObjectPair.value field pairList.add(new JaxbStringObjectPair((String) key, entry.getValue())); } org.kie.remote.jaxb.gen.List listWrapper = new org.kie.remote.jaxb.gen.List(); listWrapper.getElements().addAll(pairList); listWrapper.setType(org.kie.remote.jaxb.gen.JaxbWrapperType.MAP); return listWrapper; } else if (o.getClass().isArray()) { // convert to serializable types int length = Array.getLength(o); List<Object> serializedList = new ArrayList<Object>(length); for (int i = 0; i < length; ++i) { Object elem = convertObjectToSerializableVariant(Array.get(o, i), seenObjectsMap); serializedList.add(elem); } // convert to JaxbListWrapper org.kie.remote.jaxb.gen.List listWrapper = new org.kie.remote.jaxb.gen.List(); listWrapper.getElements().addAll(serializedList); listWrapper.setType(JaxbWrapperType.ARRAY); Class componentType = o.getClass().getComponentType(); String componentTypeName = o.getClass().getComponentType().getCanonicalName(); if (componentTypeName == null) { throw new UnsupportedOperationException( "Local or anonymous classes are not supported for serialization: " + componentType.getName()); } listWrapper.setComponentType(componentTypeName); return listWrapper; } else { return o; } } finally { seenObjectsMap.remove(o); } }
From source file:org.jolokia.converter.json.ArrayExtractor.java
private Object extractWithPath(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPath, boolean jsonify, String pPathPart) throws AttributeNotFoundException { try {/*from w w w .j ava2 s .com*/ Object obj = Array.get(pValue, Integer.parseInt(pPathPart)); return pConverter.extractObject(obj, pPath, jsonify); } catch (NumberFormatException exp) { ValueFaultHandler faultHandler = pConverter.getValueFaultHandler(); return faultHandler.handleException( new AttributeNotFoundException("Index '" + pPathPart + "' is not numeric for accessing array")); } catch (ArrayIndexOutOfBoundsException exp) { ValueFaultHandler faultHandler = pConverter.getValueFaultHandler(); return faultHandler.handleException(new AttributeNotFoundException( "Index '" + pPathPart + "' is out-of-bound for array of size " + Array.getLength(pValue))); } }
From source file:com.espertech.esper.event.util.XMLRendererImpl.java
private String renderAttElements(EventBean theEvent, int level, RendererMeta meta) { StringBuilder buf = new StringBuilder(); GetterPair[] indexProps = meta.getIndexProperties(); for (GetterPair indexProp : indexProps) { Object value = indexProp.getGetter().get(theEvent); if (value == null) { continue; }// w w w. jav a 2s . co m if (!value.getClass().isArray()) { log.warn("Property '" + indexProp.getName() + "' returned a non-array object"); continue; } for (int i = 0; i < Array.getLength(value); i++) { Object arrayItem = Array.get(value, i); if (arrayItem == null) { continue; } ident(buf, level); buf.append('<'); buf.append(indexProp.getName()); buf.append('>'); if (rendererMetaOptions.getRenderer() == null) { indexProp.getOutput().render(arrayItem, buf); } else { EventPropertyRendererContext context = rendererMetaOptions.getRendererContext(); context.setStringBuilderAndReset(buf); context.setPropertyName(indexProp.getName()); context.setPropertyValue(arrayItem); context.setIndexedPropertyIndex(i); context.setDefaultRenderer(indexProp.getOutput()); rendererMetaOptions.getRenderer().render(context); } buf.append("</"); buf.append(indexProp.getName()); buf.append('>'); buf.append(NEWLINE); } } GetterPair[] mappedProps = meta.getMappedProperties(); for (GetterPair mappedProp : mappedProps) { Object value = mappedProp.getGetter().get(theEvent); if ((value != null) && (!(value instanceof Map))) { log.warn("Property '" + mappedProp.getName() + "' expected to return Map and returned " + value.getClass() + " instead"); continue; } ident(buf, level); buf.append('<'); buf.append(mappedProp.getName()); if (value != null) { Map<String, Object> map = (Map<String, Object>) value; if (!map.isEmpty()) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); for (; it.hasNext();) { Map.Entry<String, Object> entry = it.next(); if ((entry.getKey() == null) || (entry.getValue() == null)) { continue; } buf.append(" "); buf.append(entry.getKey()); buf.append("=\""); OutputValueRenderer outputValueRenderer = OutputValueRendererFactory .getOutputValueRenderer(entry.getValue().getClass(), rendererMetaOptions); if (rendererMetaOptions.getRenderer() == null) { outputValueRenderer.render(entry.getValue(), buf); } else { EventPropertyRendererContext context = rendererMetaOptions.getRendererContext(); context.setStringBuilderAndReset(buf); context.setPropertyName(mappedProp.getName()); context.setPropertyValue(entry.getValue()); context.setMappedPropertyKey(entry.getKey()); context.setDefaultRenderer(outputValueRenderer); rendererMetaOptions.getRenderer().render(context); } buf.append("\""); } } } buf.append("/>"); buf.append(NEWLINE); } NestedGetterPair[] nestedProps = meta.getNestedProperties(); for (NestedGetterPair nestedProp : nestedProps) { Object value = nestedProp.getGetter().getFragment(theEvent); if (value == null) { continue; } if (!nestedProp.isArray()) { if (!(value instanceof EventBean)) { log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean and returned " + value.getClass() + " instead"); buf.append("null"); continue; } EventBean nestedEventBean = (EventBean) value; renderAttInner(buf, level, nestedEventBean, nestedProp); } else { if (!(value instanceof EventBean[])) { log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean[] and returned " + value.getClass() + " instead"); buf.append("null"); continue; } EventBean[] nestedEventArray = (EventBean[]) value; for (int i = 0; i < nestedEventArray.length; i++) { EventBean arrayItem = nestedEventArray[i]; renderAttInner(buf, level, arrayItem, nestedProp); } } } return buf.toString(); }
From source file:org.paxml.control.IterateTag.java
private ChildrenResultList visitArray(Context context, Object array) { if (array == null) { return null; }//from w w w .jav a2s .c o m ChildrenResultList list = null; final int len = Array.getLength(array); for (int i = 0; i < len; i++) { Object value = Array.get(array, i); list = addAll(list, visit(context, array, i + "", i, value)); } return list; }
From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java
private Object unwrapArray(Object wrapperArray, Class<?> primitiveType) { int length = Array.getLength(wrapperArray); Object primitiveArray = Array.newInstance(primitiveType, length); for (int i = 0; i < length; i++) { Array.set(primitiveArray, i, Array.get(wrapperArray, i)); }//w w w . java2 s . c o m return primitiveArray; }
From source file:com.sun.faces.el.PropertyResolverImpl.java
public Object getValue(Object base, int index) { if (base == null) { return null; }//w ww . j a v a 2s . c o m Object result = null; try { if (base.getClass().isArray()) { result = (Array.get(base, index)); } else if (base instanceof List) { result = (((List) base).get(index)); } else { if (log.isDebugEnabled()) { log.debug("getValue:Property not found at index:" + index); } throw new EvaluationException( "Bean of type " + base.getClass().getName() + " doesn't have indexed properties"); } } catch (IndexOutOfBoundsException e) { // Ignore according to spec } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("getValue:Property not found at index:" + index); } throw new EvaluationException("Error getting index " + index, t); } return result; }
From source file:Main.java
/** * Returns the <code>index</code>-th value in <code>object</code>, throwing * <code>IndexOutOfBoundsException</code> if there is no such element or * <code>IllegalArgumentException</code> if <code>object</code> is not an * instance of one of the supported types. * <p>// www .ja v a 2s.c o m * The supported types, and associated semantics are: * <ul> * <li> Map -- the value returned is the <code>Map.Entry</code> in position * <code>index</code> in the map's <code>entrySet</code> iterator, * if there is such an entry.</li> * <li> List -- this method is equivalent to the list's get method.</li> * <li> Array -- the <code>index</code>-th array entry is returned, * if there is such an entry; otherwise an <code>IndexOutOfBoundsException</code> * is thrown.</li> * <li> Collection -- the value returned is the <code>index</code>-th object * returned by the collection's default iterator, if there is such an element.</li> * <li> Iterator or Enumeration -- the value returned is the * <code>index</code>-th object in the Iterator/Enumeration, if there * is such an element. The Iterator/Enumeration is advanced to * <code>index</code> (or to the end, if <code>index</code> exceeds the * number of entries) as a side effect of this method.</li> * </ul> * * @param object the object to get a value from * @param index the index to get * @return the object at the specified index * @throws IndexOutOfBoundsException if the index is invalid * @throws IllegalArgumentException if the object type is invalid */ public static Object get(final Object object, final int index) { int i = index; if (i < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + i); } if (object instanceof Map<?, ?>) { final Map<?, ?> map = (Map<?, ?>) object; final Iterator<?> iterator = map.entrySet().iterator(); return get(iterator, i); } else if (object instanceof Object[]) { return ((Object[]) object)[i]; } else if (object instanceof Iterator<?>) { final Iterator<?> it = (Iterator<?>) object; while (it.hasNext()) { i--; if (i == -1) { return it.next(); } it.next(); } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } else if (object instanceof Collection<?>) { final Iterator<?> iterator = ((Collection<?>) object).iterator(); return get(iterator, i); } else if (object instanceof Enumeration<?>) { final Enumeration<?> it = (Enumeration<?>) object; while (it.hasMoreElements()) { i--; if (i == -1) { return it.nextElement(); } else { it.nextElement(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { return Array.get(object, i); } catch (final IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } }
From source file:org.eclipse.e4.emf.internal.xpath.helper.ValueUtils.java
@SuppressWarnings("unchecked") public static Object getValue(Object collection, int index) { collection = getValue(collection);//from w ww. j av a 2 s . c o m Object value = collection; if (collection != null) { if (collection.getClass().isArray()) { if (index < 0 || index >= Array.getLength(collection)) { return null; } value = Array.get(collection, index); } else if (collection instanceof List) { if (index < 0 || index >= ((List<?>) collection).size()) { return null; } value = ((List<Object>) collection).get(index); } else if (collection instanceof Collection) { int i = 0; Iterator<Object> it = ((Collection<Object>) collection).iterator(); for (; i < index; i++) { it.next(); } if (it.hasNext()) { value = it.next(); } else { value = null; } } } return value; }