List of usage examples for java.lang.reflect Array set
public static native void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:com.astamuse.asta4d.web.form.flow.base.BasicFormFlowHandlerTrait.java
/** * Assign array value to cascade forms of array type from context by recursively self call. * /*ww w .j ava 2 s .c o m*/ * @param formCls * @param form * @param currentContext * @param indexes * @return * @throws Exception */ default T assignArrayValueFromContext(Class formCls, T form, Context currentContext, int[] indexes) throws Exception { List<AnnotatedPropertyInfo> list = AnnotatedPropertyUtil.retrieveProperties(formCls); for (final AnnotatedPropertyInfo field : list) { CascadeFormField cff = field.getAnnotation(CascadeFormField.class); if (cff != null) { if (field.getType().isArray()) {// a cascade form for array if (field.retrieveValue(form) != null) { continue; } if (StringUtils.isEmpty(cff.arrayLengthField())) { continue; } List<AnnotatedPropertyInfo> arrayLengthFieldList = AnnotatedPropertyUtil .retrievePropertyByName(formCls, cff.arrayLengthField()); if (CollectionUtils.isEmpty(arrayLengthFieldList)) { throw new NullPointerException( "specified array length field [" + cff.arrayLengthField() + "] was not found"); } // we only need one AnnotatedPropertyInfo arrayLengthField = arrayLengthFieldList.get(0); Integer len = (Integer) arrayLengthField.retrieveValue(form); if (len == null) { // throw new NullPointerException("specified array length field [" + cff.arrayLengthField() + "] is null"); len = 0; } final Object[] array = (Object[]) Array.newInstance(field.getType().getComponentType(), len); for (int i = 0; i < len; i++) { final int seq = i; final int[] newIndex = ArrayUtils.add(indexes, seq); Context.with(new DelatedContext(currentContext) { protected String convertKey(String scope, String key) { if (scope.equals(WebApplicationContext.SCOPE_QUERYPARAM)) { return rewriteArrayIndexPlaceHolder(key, newIndex); } else { return key; } } }, new Runnable() { @Override public void run() { try { Object subform = field.getType().getComponentType().newInstance(); InjectUtil.injectToInstance(subform); Array.set(array, seq, subform); } catch (Exception e) { throw new RuntimeException(e); } } });// end runnable and context.with assignArrayValueFromContext(field.getType().getComponentType(), (T) array[seq], currentContext, newIndex); } // end for loop field.assignValue(form, array); } else { // a cascade form for not array assignArrayValueFromContext(field.getType(), (T) field.retrieveValue(form), currentContext, indexes); } } } return form; }
From source file:wicket.util.lang.Objects.java
/** * Returns the value converted numerically to the given class type * //from w ww . j a v a2 s .c om * This method also detects when arrays are being converted and converts the * components of one array to the type of the other. * * @param value * an object to be converted to the given type * @param toType * class type to be converted to * @return converted value of the type given, or value if the value cannot * be converted to the given type. */ public static 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 = new Integer((int) longValue(value)); } if ((toType == Double.class) || (toType == Double.TYPE)) { result = new Double(doubleValue(value)); } if ((toType == Boolean.class) || (toType == Boolean.TYPE)) { result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE; } if ((toType == Byte.class) || (toType == Byte.TYPE)) { result = new Byte((byte) longValue(value)); } if ((toType == Character.class) || (toType == Character.TYPE)) { result = new Character((char) longValue(value)); } if ((toType == Short.class) || (toType == Short.TYPE)) { result = new Short((short) longValue(value)); } if ((toType == Long.class) || (toType == Long.TYPE)) { result = new Long(longValue(value)); } if ((toType == Float.class) || (toType == Float.TYPE)) { result = new Float(doubleValue(value)); } if (toType == BigInteger.class) { result = bigIntValue(value); } if (toType == BigDecimal.class) { result = bigDecValue(value); } if (toType == String.class) { result = stringValue(value); } } } else { if (toType.isPrimitive()) { result = primitiveDefaults.get(toType); } } return result; }
From source file:org.apache.felix.webconsole.internal.compendium.ConfigManager.java
private Object getArray(int type, Vector values) { int totalSize = values.size(); // short cut for string array if (type == AttributeDefinition.STRING) { return values.toArray(new String[totalSize]); }//from ww w . j a v a 2 s.c o m Object tempArray; switch (type) { case AttributeDefinition.FLOAT: tempArray = new float[totalSize]; case AttributeDefinition.LONG: tempArray = new long[totalSize]; case AttributeDefinition.INTEGER: tempArray = new int[totalSize]; case AttributeDefinition.SHORT: tempArray = new short[totalSize]; case AttributeDefinition.BOOLEAN: tempArray = new boolean[totalSize]; case AttributeDefinition.BYTE: tempArray = new byte[totalSize]; case AttributeDefinition.CHARACTER: tempArray = new char[totalSize]; case AttributeDefinition.DOUBLE: tempArray = new double[totalSize]; default: // unexpected, but assume string tempArray = new String[totalSize]; } for (int i = 0; i < totalSize; i++) { Array.set(tempArray, i, values.get(i)); } return tempArray; }
From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java
/** * ??//w ww . j av a 2 s. com * @param array * @param elementType * @return * @date 2012-2-20 */ protected Object convertArrayToArray(Object array, Type elementType) throws ConvertException { Object result = null; int len = Array.getLength(array); result = instance(elementType, len); for (int i = 0; i < len; i++) { Object v = convertObjectToType(Array.get(array, i), elementType); Array.set(result, i, v); } return result; }
From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java
protected Object convertToTypedArray(Object input, String propertyName, Class componentType) { if (input instanceof Collection) { // Convert Collection elements to array elements. Collection coll = (Collection) input; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator it = coll.iterator(); it.hasNext(); i++) { Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, it.next(), componentType);/* w w w. j a v a2 s. com*/ Array.set(result, i, value); } return result; } else if (input.getClass().isArray()) { // Convert array elements, if necessary. if (componentType.equals(input.getClass().getComponentType()) && !this.propertyEditorRegistry.hasCustomEditorForElement(componentType, propertyName)) { return input; } int arrayLength = Array.getLength(input); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, Array.get(input, i), componentType); Array.set(result, i, value); } return result; } else { // A plain value: convert it to an array with a single component. Object result = Array.newInstance(componentType, 1); Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, 0), null, input, componentType); Array.set(result, 0, value); return result; } }
From source file:org.apache.struts.action.DynaActionForm.java
/** * <p>Set the value of an indexed property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * @throws ConversionException if the specified value cannot be * converted to the type required for * this property * @throws NullPointerException if there is no property of the * specified name * @throws IllegalArgumentException if the specified property exists, but * is not indexed * @throws IndexOutOfBoundsException if the specified index is outside the * range of the underlying property *///w w w . j a va2 s .c om public void set(String name, int index, Object value) { Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { Array.set(prop, index, value); } else if (prop instanceof List) { try { ((List) prop).set(index, value); } catch (ClassCastException e) { throw new ConversionException(e.getMessage()); } } else { throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"); } }
From source file:javadz.beanutils.ConvertUtilsBean.java
/** * Convert an array of specified values to an array of objects of the * specified class (if possible). If the specified Java class is itself * an array class, this class will be the type of the returned value. * Otherwise, an array will be constructed whose component type is the * specified class.// w w w . j a va 2 s . c om * * @param values Array of values to be converted * @param clazz Java array or element class to be converted to * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ public Object convert(String[] values, Class clazz) { Class type = clazz; if (clazz.isArray()) { type = clazz.getComponentType(); } if (log.isDebugEnabled()) { log.debug("Convert String[" + values.length + "] to class '" + type.getName() + "[]'"); } Converter converter = lookup(type); if (converter == null) { converter = lookup(String.class); } if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } Object array = Array.newInstance(type, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, converter.convert(type, values[i])); } return (array); }
From source file:com.espertech.esper.epl.core.SelectExprInsertEventBeanFactory.java
private static SelectExprProcessor initializeCtorInjection(EventType eventType, ExprEvaluator[] exprEvaluators, StreamTypeService typeService, Object[] expressionReturnTypes, EngineImportService engineImportService, EventAdapterService eventAdapterService) throws ExprValidationException { BeanEventType beanEventType = (BeanEventType) eventType; Class[] ctorTypes = new Class[expressionReturnTypes.length]; ExprEvaluator[] evaluators = new ExprEvaluator[exprEvaluators.length]; for (int i = 0; i < expressionReturnTypes.length; i++) { Object columnType = expressionReturnTypes[i]; if (columnType instanceof Class || columnType == null) { ctorTypes[i] = (Class) expressionReturnTypes[i]; evaluators[i] = exprEvaluators[i]; continue; }/*from www . ja v a 2 s . c o m*/ if (columnType instanceof EventType) { EventType columnEventType = (EventType) columnType; final Class returnType = columnEventType.getUnderlyingType(); final ExprEvaluator inner = exprEvaluators[i]; evaluators[i] = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = (EventBean) inner.evaluate(eventsPerStream, isNewData, exprEvaluatorContext); if (theEvent != null) { return theEvent.getUnderlying(); } return null; } public Class getType() { return returnType; } }; ctorTypes[i] = returnType; continue; } // handle case where the select-clause contains an fragment array if (columnType instanceof EventType[]) { EventType columnEventType = ((EventType[]) columnType)[0]; final Class componentReturnType = columnEventType.getUnderlyingType(); final ExprEvaluator inner = exprEvaluators[i]; evaluators[i] = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { Object result = inner.evaluate(eventsPerStream, isNewData, exprEvaluatorContext); if (!(result instanceof EventBean[])) { return null; } EventBean[] events = (EventBean[]) result; Object values = Array.newInstance(componentReturnType, events.length); for (int i = 0; i < events.length; i++) { Array.set(values, i, events[i].getUnderlying()); } return values; } public Class getType() { return componentReturnType; } }; continue; } String message = "Invalid assignment of expression " + i + " returning type '" + columnType + "', column and parameter types mismatch"; throw new ExprValidationException(message); } FastConstructor fctor; try { Constructor ctor = engineImportService.resolveCtor(beanEventType.getUnderlyingType(), ctorTypes); FastClass fastClass = FastClass.create(Thread.currentThread().getContextClassLoader(), beanEventType.getUnderlyingType()); fctor = fastClass.getConstructor(ctor); } catch (EngineImportException ex) { throw new ExprValidationException("Failed to find a suitable constructor for bean-event type '" + eventType.getName() + "': " + ex.getMessage(), ex); } EventBeanManufacturerCtor eventManufacturer = new EventBeanManufacturerCtor(fctor, beanEventType, eventAdapterService); return new SelectExprInsertNativeNoWiden(eventType, eventManufacturer, evaluators); }
From source file:org.datanucleus.store.scalaris.fieldmanager.FetchFieldManager.java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected Object fetchObjectFieldInternal(AbstractMemberMetaData mmd, String memberName, ClassLoaderResolver clr) throws JSONException { RelationType relationType = mmd.getRelationType(clr); if (relationType == RelationType.NONE) { return fetchObjectFieldInternal_RelationTypeNone(mmd, memberName, clr); } else if (RelationType.isRelationSingleValued(relationType)) { // Persistable object - retrieve the string form of the identity, // and find the object String idStr = (String) result.get(memberName); if (idStr == null) { return null; }/* w w w. ja v a 2 s . com*/ AbstractClassMetaData acmd = ec.getMetaDataManager().getMetaDataForClass(mmd.getType(), clr); return getNestedObjectById(idStr, acmd, ec); } else if (RelationType.isRelationMultiValued(relationType)) { if (mmd.hasCollection()) { // Collection<PC> JSONArray array = (JSONArray) result.get(memberName); Collection<Object> coll; try { Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), mmd.getOrderMetaData() != null); coll = (Collection<Object>) instanceType.newInstance(); } catch (Exception e) { throw new NucleusDataStoreException(e.getMessage(), e); } AbstractClassMetaData elementCmd = mmd.getCollection() .getElementClassMetaData(ec.getClassLoaderResolver(), ec.getMetaDataManager()); for (int i = 0; i < array.length(); i++) { String idStr = (String) array.get(i); if (idStr == null) { coll.add(idStr); } else { Object element = getNestedObjectById(idStr, elementCmd, ec); if (element != null) { coll.add(element); } } } if (op != null) { return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), coll, true); } return coll; } else if (mmd.hasArray()) { // PC[] JSONArray array = (JSONArray) result.get(memberName); Object arrayField = Array.newInstance(mmd.getType().getComponentType(), array.length()); AbstractClassMetaData elementCmd = mmd.getCollection() .getElementClassMetaData(ec.getClassLoaderResolver(), ec.getMetaDataManager()); for (int i = 0; i < array.length(); i++) { String idStr = (String) array.get(i); if (idStr == null) { Array.set(arrayField, i, idStr); } else { Object element = getNestedObjectById(idStr, elementCmd, ec); Array.set(arrayField, i, element); } } if (op != null) { return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), arrayField, true); } return arrayField; } else if (mmd.hasMap()) { // Map<Non-PC, PC>, Map<PC, PC>, Map<PC, Non-PC> JSONObject mapVal = (JSONObject) result.get(memberName); Map map; try { Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false); map = (Map) instanceType.newInstance(); } catch (Exception e) { throw new NucleusDataStoreException(e.getMessage(), e); } AbstractClassMetaData keyCmd = mmd.getMap().getKeyClassMetaData(clr, ec.getMetaDataManager()); AbstractClassMetaData valCmd = mmd.getMap().getValueClassMetaData(clr, ec.getMetaDataManager()); Iterator<?> keyIter = mapVal.keys(); while (keyIter.hasNext()) { Object jsonKey = keyIter.next(); Object key = null; if (keyCmd != null) { // The jsonKey is the string form of the identity String idStr = (String) jsonKey; key = getNestedObjectById(idStr, keyCmd, ec); } else { Class<?> keyCls = ec.getClassLoaderResolver().classForName(mmd.getMap().getKeyType()); key = TypeConversionHelper.convertTo(jsonKey, keyCls); } Object jsonVal = mapVal.get((String) key); Object val = null; if (valCmd != null) { // The jsonVal is the string form of the identity String idStr = (String) jsonVal; val = getNestedObjectById(idStr, valCmd, ec); } else { Class valCls = ec.getClassLoaderResolver().classForName(mmd.getMap().getValueType()); val = TypeConversionHelper.convertTo(jsonVal, valCls); } map.put(key, val); } if (op != null) { return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), map, true); } return map; } } throw new NucleusException( "Dont currently support field " + mmd.getFullFieldName() + " of type " + mmd.getTypeName()); }
From source file:org.apache.s4.util.LoadGenerator.java
@SuppressWarnings("unchecked") public static Object makeArray(Property property, JSONArray jsonArray) { Property componentProperty = property.getComponentProperty(); Class clazz = componentProperty.getType(); int size = jsonArray.length(); Object array = Array.newInstance(clazz, size); try {/*from w ww.ja v a 2 s . c om*/ for (int i = 0; i < size; i++) { Object value = jsonArray.get(i); Object adjustedValue = makeSettableValue(componentProperty, value); Array.set(array, i, adjustedValue); } } catch (JSONException je) { throw new RuntimeException(je); } return array; }