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.struts.taglib.logic.IterateTag.java
/** * Construct an iterator for the specified collection, and begin * looping through the body once per element. * * @exception JspException if a JSP exception has occurred *///www . ja v a2 s. com public int doStartTag() throws JspException { // Acquire the collection we are going to iterate over Object collection = this.collection; if (collection == null) { collection = RequestUtils.lookup(pageContext, name, property, scope); } if (collection == null) { JspException e = new JspException(messages.getMessage("iterate.collection")); RequestUtils.saveException(pageContext, e); throw e; } // Construct an iterator for this collection if (collection.getClass().isArray()) { try { // If we're lucky, it is an array of objects // that we can iterate over with no copying iterator = Arrays.asList((Object[]) collection).iterator(); } catch (ClassCastException e) { // Rats -- it is an array of primitives int length = Array.getLength(collection); ArrayList c = new ArrayList(length); for (int i = 0; i < length; i++) { c.add(Array.get(collection, i)); } iterator = c.iterator(); } } else if (collection instanceof Collection) { iterator = ((Collection) collection).iterator(); } else if (collection instanceof Iterator) { iterator = (Iterator) collection; } else if (collection instanceof Map) { iterator = ((Map) collection).entrySet().iterator(); } else if (collection instanceof Enumeration) { iterator = IteratorUtils.asIterator((Enumeration) collection); } else { JspException e = new JspException(messages.getMessage("iterate.iterator")); RequestUtils.saveException(pageContext, e); throw e; } // Calculate the starting offset if (offset == null) { offsetValue = 0; } else { try { offsetValue = Integer.parseInt(offset); } catch (NumberFormatException e) { Integer offsetObject = (Integer) RequestUtils.lookup(pageContext, offset, null); if (offsetObject == null) { offsetValue = 0; } else { offsetValue = offsetObject.intValue(); } } } if (offsetValue < 0) { offsetValue = 0; } // Calculate the rendering length if (length == null) { lengthValue = 0; } else { try { lengthValue = Integer.parseInt(length); } catch (NumberFormatException e) { Integer lengthObject = (Integer) RequestUtils.lookup(pageContext, length, null); if (lengthObject == null) { lengthValue = 0; } else { lengthValue = lengthObject.intValue(); } } } if (lengthValue < 0) { lengthValue = 0; } lengthCount = 0; // Skip the leading elements up to the starting offset for (int i = 0; i < offsetValue; i++) { if (iterator.hasNext()) { iterator.next(); } } // Store the first value and evaluate, or skip the body if none if (iterator.hasNext()) { Object element = iterator.next(); if (element == null) { pageContext.removeAttribute(id); } else { pageContext.setAttribute(id, element); } lengthCount++; started = true; if (indexId != null) { pageContext.setAttribute(indexId, new Integer(getIndex())); } return (EVAL_BODY_TAG); } else { return (SKIP_BODY); } }
From source file:org.crazydog.util.spring.ObjectUtils.java
/** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array.//from ww w. ja va 2 s. c om * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class<?> wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
From source file:jp.terasoluna.fw.web.struts.form.DynaValidatorActionFormEx.java
/** * CfbNXtv?peBZbg?B//from w w w . j a va 2 s. c om * * <p> * StrutsDynaActionFormv?peB^ * Listz^gpO??A * TCY?AITCY * ?X?A???g?B * </p> * * @param name Zbg?tB?[h * @param index Zbg?CfbNX * @param value Zbg?tB?[hl */ @SuppressWarnings("unchecked") @Override public void set(String name, int index, Object value) { if (log.isDebugEnabled()) { log.debug("set(" + name + ", " + index + ", " + value + ") called."); } Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { if (index < Array.getLength(prop)) { Array.set(prop, index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); // ?VKz?? Object newArray = Array.newInstance(prop.getClass().getComponentType(), index + 1); // zR|?[lgRs?[ System.arraycopy(prop, 0, newArray, 0, Array.getLength(prop)); // R|?[lgZbg Array.set(newArray, index, value); // Q?Rs?[ prop = newArray; } dynaValues.put(name, prop); } else if (prop instanceof List) { if (index < ((List) prop).size()) { ((List) prop).set(index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); Object[] oldValues = ((List) prop).toArray(); Object[] newValues = (Object[]) Array.newInstance(oldValues.getClass().getComponentType(), index + 1); System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[index] = value; ((List) prop).clear(); ((List) prop).addAll(Arrays.asList(newValues)); } dynaValues.put(name, prop); } else { throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"); } }
From source file:edu.cmu.cs.lti.util.general.BasicConvenience.java
/** * Given 2 arrays which may be arrays of other things, * determine if they have exactly the same dimensions, to some level * @param a1//from www . jav a2 s . c o m * @param a2 * @param levels 1 means an array X[], 2 means X[] [], etc. * @return true if all dimensions are the same */ public static boolean allArrayDimensionsEqual(Object a1, Object a2, int levels) { int length = Array.getLength(a1); if (length != Array.getLength(a2)) { return false; } if (levels > 1) { for (int i = 0; i < length; i++) { if (!allArrayDimensionsEqual(Array.get(a1, i), Array.get(a2, i), levels - 1)) { return false; } } } return true; }
From source file:org.apache.myfaces.config.ManagedBeanBuilder.java
@SuppressWarnings("unchecked") private void initializeProperties(FacesContext facesContext, ManagedBean beanConfiguration, Object bean) { ELResolver elResolver = facesContext.getApplication().getELResolver(); ELContext elContext = facesContext.getELContext(); for (ManagedProperty property : beanConfiguration.getManagedProperties()) { Object value = null;/*w w w . j a v a2 s. c o m*/ switch (property.getType()) { case ManagedProperty.TYPE_LIST: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.ArrayList, // otherwise use the returned Object ... if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new ArrayList<Object>() : value; if (value instanceof List) { initializeList(facesContext, property.getListEntries(), (List<Object>) value); } else if (value != null && value.getClass().isArray()) { int length = Array.getLength(value); ArrayList<Object> temp = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { temp.add(Array.get(value, i)); } initializeList(facesContext, property.getListEntries(), temp); value = Array.newInstance(value.getClass().getComponentType(), temp.size()); length = temp.size(); for (int i = 0; i < length; i++) { Array.set(value, i, temp.get(i)); } } else { value = new ArrayList<Object>(); initializeList(facesContext, property.getListEntries(), (List<Object>) value); } break; case ManagedProperty.TYPE_MAP: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.HashMap, // otherwise use the returned java.util.Map . if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new HashMap<Object, Object>() : value; if (!(value instanceof Map)) { value = new HashMap<Object, Object>(); } initializeMap(facesContext, property.getMapEntries(), (Map<Object, Object>) value); break; case ManagedProperty.TYPE_NULL: break; case ManagedProperty.TYPE_VALUE: // check for correct scope of a referenced bean if (!isInValidScope(facesContext, property, beanConfiguration)) { throw new FacesException("Property " + property.getPropertyName() + " references object in a scope with shorter lifetime than the target scope " + beanConfiguration.getManagedBeanScope()); } value = property.getRuntimeValue(facesContext); break; default: throw new FacesException("unknown ManagedProperty type: " + property.getType()); } Class<?> propertyClass = null; if (property.getPropertyClass() == null) { propertyClass = elResolver.getType(elContext, bean, property.getPropertyName()); } else { propertyClass = ClassUtils.simpleJavaTypeToClass(property.getPropertyClass()); } if (null == propertyClass) { throw new IllegalArgumentException( "unable to find the type of property " + property.getPropertyName()); } Object coercedValue = coerceToType(facesContext, value, propertyClass); elResolver.setValue(elContext, bean, property.getPropertyName(), coercedValue); } }
From source file:org.apache.myfaces.ov2021.config.ManagedBeanBuilder.java
@SuppressWarnings("unchecked") private void initializeProperties(FacesContext facesContext, ManagedBean beanConfiguration, Object bean) { ELResolver elResolver = facesContext.getApplication().getELResolver(); ELContext elContext = facesContext.getELContext(); for (ManagedProperty property : beanConfiguration.getManagedProperties()) { Object value = null;/*from w w w . j a va2 s . com*/ switch (property.getType()) { case ManagedProperty.TYPE_LIST: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.ArrayList, // otherwise use the returned Object ... if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new ArrayList<Object>() : value; if (value instanceof List) { initializeList(facesContext, property.getListEntries(), (List<Object>) value); } else if (value != null && value.getClass().isArray()) { int length = Array.getLength(value); ArrayList<Object> temp = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { temp.add(Array.get(value, i)); } initializeList(facesContext, property.getListEntries(), temp); value = Array.newInstance(value.getClass().getComponentType(), temp.size()); length = temp.size(); for (int i = 0; i < length; i++) { Array.set(value, i, temp.get(i)); } } else { value = new ArrayList<Object>(); initializeList(facesContext, property.getListEntries(), (List<Object>) value); } break; case ManagedProperty.TYPE_MAP: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.HashMap, // otherwise use the returned java.util.Map . if (PropertyUtils.isReadable(bean, property.getPropertyName())) value = elResolver.getValue(elContext, bean, property.getPropertyName()); value = value == null ? new HashMap<Object, Object>() : value; if (!(value instanceof Map)) { value = new HashMap<Object, Object>(); } initializeMap(facesContext, property.getMapEntries(), (Map<Object, Object>) value); break; case ManagedProperty.TYPE_NULL: break; case ManagedProperty.TYPE_VALUE: // check for correct scope of a referenced bean if (!isInValidScope(facesContext, property, beanConfiguration)) { throw new FacesException("Property " + property.getPropertyName() + " references object in a scope with shorter lifetime than the target scope " + beanConfiguration.getManagedBeanScope()); } value = property.getRuntimeValue(facesContext); break; } Class<?> propertyClass = null; if (property.getPropertyClass() == null) { propertyClass = elResolver.getType(elContext, bean, property.getPropertyName()); } else { propertyClass = ClassUtils.simpleJavaTypeToClass(property.getPropertyClass()); } if (null == propertyClass) { throw new IllegalArgumentException( "unable to find the type of property " + property.getPropertyName()); } Object coercedValue = coerceToType(facesContext, value, propertyClass); elResolver.setValue(elContext, bean, property.getPropertyName(), coercedValue); } }
From source file:org.kmnet.com.fw.web.message.MessagesPanelTag.java
/** * Writes the messages which have been set in the model * <p>//w ww. ja v a 2 s. co m * If messages stored in the model is in the form of a class that extends * {@code Iterable} or an Array, {@link #writeMessage(TagWriter, Object)} is * called multiple times, to write<br> * {@link #innerElement} and messages.<br> * * If there is only a single message, this method calls * {@link #writeMessage(TagWriter, Object)} only once * </p> * * @param tagWriter * @param messages * @throws JspException * If {@link JspException} occurs in caller writeMessage */ protected void writeMessages(TagWriter tagWriter, Object messages) throws JspException { Class<?> clazz = messages.getClass(); if (Iterable.class.isAssignableFrom(clazz)) { Iterable<?> col = (Iterable<?>) messages; for (Object message : col) { writeMessage(tagWriter, message); } } else if (clazz.isArray()) { Class<?> type = clazz.getComponentType(); if (Object.class.isAssignableFrom(type)) { Object[] arr = (Object[]) messages; for (Object message : arr) { writeMessage(tagWriter, message); } } else { int len = Array.getLength(messages); for (int i = 0; i < len; i++) { Object message = Array.get(messages, i); writeMessage(tagWriter, message); } } } else { writeMessage(tagWriter, messages); } }
From source file:cz.zcu.kiv.eegdatabase.logic.indexing.PojoIndexer.java
/** * Creates a document for indexing. The document consists of values of fields having indexing annotations. * Depending on the annotation type, fields are either put to the document or traversed recursively to pick * property values of nested objects.//from ww w. j ava 2 s . c o m * @param instance Parent object to be indexed, * @param level Current level of traversal. Can be either parent or child level. In case of the parent level, the * algorithm can continue indexing the child elements located in the child level. In both levels * indexing of String and primitive types is allowed. * @return Field-value pairs representing a document to be indexed. * @throws IllegalAccessException * @throws NoSuchMethodException * @throws InvocationTargetException */ private Map<String, Object> getDocumentFromAnnotatedFields(Object instance, int level) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Map<String, Object> solrFields = new HashMap<String, Object>(); Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { // check presence of the SolrField annotation for each field if (field.isAnnotationPresent(SolrField.class)) { field.setAccessible(true); // necessary since all fields are private Object fieldValue = field.get(instance); // actual value of the annotated field log.debug(instance.getClass().getName()); // null values are skipped if (fieldValue == null) { continue; } String fieldName = field.getAnnotation(SolrField.class).name().getValue(); if (level == LEVEL_CHILD) { fieldName = "child_" + fieldName; } log.debug("Indexing - field: " + fieldName + " value: " + fieldValue.toString()); // POJO has more fields having the same annotation parameter if (solrFields.containsKey(fieldName)) { solrFields.put(fieldName, solrFields.get(fieldName) + " " + fieldValue); } // the annotated value is being read for the first time else { solrFields.put(fieldName, fieldValue); } } // traverse collections and objects of the parent object else if (level == LEVEL_PARENT) { // check if it is a collection if (field.isAnnotationPresent(Indexed.class) && Collection.class.isAssignableFrom(field.getType())) { field.setAccessible(true); // necessary since all fields are private Object collectionInstance = field.get(instance); if (collectionInstance == null) { continue; } // convert the collection to an array to enable transparent manipulation independent // on the specific collection subclass Method objectToArray = field.getType().getMethod("toArray"); Object array = objectToArray.invoke(collectionInstance); // get array size int length = Array.getLength(array); Map<String, List<Object>> solrFieldsChildren = new HashMap<String, List<Object>>(); for (int i = 0; i < length; i++) { Object element = Array.get(array, i); // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(element, LEVEL_CHILD); // add all field-value pairs of each object of the collection to the map of the whole collection for (Map.Entry<String, Object> entry : solrFieldsChild.entrySet()) { if (solrFieldsChildren.containsKey(entry.getKey())) { List<Object> list = solrFieldsChildren.get(entry.getKey()); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } else { List<Object> list = new ArrayList<Object>(); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } } } // add the index values of the children from the collection to the parent fields solrFields.putAll(solrFieldsChildren); } // check if it's an object else if (field.isAnnotationPresent(Indexed.class) && field.getType().isInstance(Object.class)) { // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(field.get(instance), LEVEL_CHILD); solrFields.putAll(solrFieldsChild); } } } return solrFields; }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
@SuppressWarnings({ "unchecked", "unchecked" }) public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException, IllegalAccessException {/*from w ww.j av a2 s .c o m*/ try { List<Method> validMethods = new ArrayList<>(); for (Method method : clazz.getMethods()) { Class<?>[] parameterTypes = null; if (!method.getName().equals(methodName)) { continue; } parameterTypes = method.getParameterTypes(); if (method.isVarArgs()) { if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) { parameterTypes = null; continue; } } else { if (parameterTypes.length != args.length) { parameterTypes = null; continue; } } if (method.isVarArgs()) { boolean matches = false; // check non vararg part for (int i = 0; i < parameterTypes.length - 1; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } // check rest for (int i = parameterTypes.length - 1; i < args.length; i++) { Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType(); matches = checkMatch(arrayType, args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } else { boolean matches = true; for (int i = 0; i < parameterTypes.length; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } } if (!validMethods.isEmpty()) { Method method = validMethods.get(0); for (int i = 1; i < validMethods.size(); i++) { Method targetMethod = validMethods.get(i); Class<?>[] currentParams = method.getParameterTypes(); Class<?>[] targetParams = targetMethod.getParameterTypes(); if (method.isVarArgs() && targetMethod.isVarArgs()) { for (int j = 0; j < currentParams.length; j++) { if (currentParams[j].isAssignableFrom(targetParams[j])) { method = targetMethod; break; } } } else if (method.isVarArgs()) { //usually, non-vararg is more specific method. So we use that method = targetMethod; } else if (targetMethod.isVarArgs()) { //do nothing } else { for (int j = 0; j < currentParams.length; j++) { if (targetParams[j].isEnum()) { // enum will be handled later method = targetMethod; break; } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method method = targetMethod; break; } } } } method.setAccessible(true); for (int i = 0; i < args.length; i++) { Class<?>[] parameterTypes = method.getParameterTypes(); if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) { try { args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]); } catch (IllegalArgumentException ex1) { // Some overloaded methods already has // String to Enum conversion // So just lets see if one exists Class<?>[] types = new Class<?>[args.length]; for (int k = 0; k < args.length; k++) types[k] = args[k].getClass(); try { Method alternative = clazz.getMethod(methodName, types); return alternative.invoke(obj, args); } catch (NoSuchMethodException ex2) { throw new RuntimeException( "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i] + "] or find appropriate method but found nothing. Make sure" + " that the value [" + args[i] + "] matches exactly with one of the Enums in [" + parameterTypes[i] + "] or the method you are looking exists."); } } } } if (method.isVarArgs()) { Class<?>[] parameterTypes = method.getParameterTypes(); Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(), args.length - parameterTypes.length + 1); for (int k = 0; k < Array.getLength(varargs); k++) { Array.set(varargs, k, args[parameterTypes.length - 1 + k]); } Object[] newArgs = new Object[parameterTypes.length]; for (int k = 0; k < newArgs.length - 1; k++) { newArgs[k] = args[k]; } newArgs[newArgs.length - 1] = varargs; args = newArgs; } return method.invoke(obj, args); } if (args.length > 0) { StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName())); for (int i = 1; i < args.length; i++) { builder.append(", " + args[i].getClass().getSimpleName()); } throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")"); } else { throw new NoSuchMethodException(methodName + "()"); } } catch (NullPointerException e) { StringBuilder builder = new StringBuilder(String.valueOf(args[0])); for (int i = 1; i < args.length; i++) builder.append("," + String.valueOf(args[i])); throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")"); } }