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.AbstractFormFlowHandler.java
/** * Sub classes can override this method to do some interception around form instance generation, especially some post processes. * <p>// w w w . ja va 2 s .co m * <b>NOTE:</b> DO NOT replace this method completely at sub class, if you want to do some customized form retrieving, override the * method {@link #retrieveFormInstance(Map, String)} instead. * * @return */ protected T generateFormInstanceFromContext() { try { final T form = (T) InjectUtil.retrieveContextDataSetInstance(formCls, FORM_PRE_DEFINED, ""); List<AnnotatedPropertyInfo> list = AnnotatedPropertyUtil.retrieveProperties(formCls); Context currentContext = Context.getCurrentThreadContext(); for (final AnnotatedPropertyInfo field : list) { CascadeFormField cff = field.getAnnotation(CascadeFormField.class); if (cff != null) { if (field.retrieveValue(form) != null) { continue; } if (StringUtils.isEmpty(cff.arrayLengthField())) { continue; } AnnotatedPropertyInfo arrayLengthField = AnnotatedPropertyUtil.retrievePropertyByName(formCls, cff.arrayLengthField()); if (arrayLengthField == null) { throw new NullPointerException( "specified array length field [" + cff.arrayLengthField() + "] was not found"); } 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; Context.with(new DelatedContext(currentContext) { protected String convertKey(String scope, String key) { if (scope.equals(WebApplicationContext.SCOPE_QUERYPARAM)) { return rewriteArrayIndexPlaceHolder(key, seq); } 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 } // end for loop field.assginValue(form, array); } } return form; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.struts.config.FormPropertyConfig.java
/** * <p>Return an object representing the initial value of this property. * This is calculated according to the following algorithm:</p> * * <ul>/*from ww w .j a v a2 s . c om*/ * * <li>If the value you have specified for the <code>type</code> property * represents an array (i.e. it ends with "[]"): * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an instance of the specified array type.</li> * * <li>If you have not specified a value for the <code>initial</code> * property, an array of the length specified by the <code>size</code> * property will be created. Each element of the array will be * instantiated via the zero-args constructor on the specified class (if * any). Otherwise, <code>null</code> will be returned.</li> * * </ul></li> * * <li>If the value you have specified for the <code>type</code> property * does not represent an array: * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an object instance.</li> * * <li>If you have not specified a value for the <code>initial</code> * attribute, Struts will instantiate an instance via the zero-args * constructor on the specified class (if any). Otherwise, * <code>null</code> will be returned.</li> * * </ul></li> * * </ul> */ public Object initial() { Object initialValue = null; try { Class clazz = getTypeClass(); if (clazz.isArray()) { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = Array.newInstance(clazz.getComponentType(), size); if (!(clazz.getComponentType().isPrimitive())) { for (int i = 0; i < size; i++) { try { Array.set(initialValue, i, clazz.getComponentType().newInstance()); } catch (Throwable t) { log.error("Unable to create instance of " + clazz.getName() + " for property=" + name + ", type=" + type + ", initial=" + initial + ", size=" + size + "."); //FIXME: Should we just dump the entire application/module ? } } } } } else { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = clazz.newInstance(); } } } catch (Throwable t) { initialValue = null; } return (initialValue); }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
public <T> T generateRandom(Type type, Map<String, Type> itestGenericMap, ITestContext iTestContext) { ITestParamState iTestState = iTestContext.getCurrentParam(); Class<?> clazz = ITestTypeUtil.getRawClass(type); Class<?> requestedClass = getClassFromParam(iTestState); if (null != iTestState && null != iTestState.getAttribute(ITestConstants.ATTRIBUTE_DEFINITION)) { ITestParamState iTestStateLoaded = iTestConfig.getITestParamLoader() .loadITestParam(null == requestedClass ? clazz : requestedClass, iTestState.getAttribute(ITestConstants.ATTRIBUTE_DEFINITION)) .getElement(ITestConstants.THIS); iTestState = iTestConfig.getITestParamsMerger().merge( new ITestParamAssignmentImpl("", iTestStateLoaded), new ITestParamAssignmentImpl("", iTestState)); iTestContext.replaceCurrentState(iTestState); }/*from ww w . j a v a 2s . c om*/ Object res; if (ITestParamState.class == clazz) { res = processITestState(iTestContext); } else if (null != iTestState && null == iTestState.getSizeParam() && null == iTestState.getValue()) { res = null; } else if (null != iTestState && null != iTestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE)) { res = iTestContext.findGeneratedObject(iTestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE)); } else if (PROXY_CLASS == requestedClass) { res = newDynamicProxy(type, itestGenericMap, iTestContext); } else if (Collection.class.isAssignableFrom(clazz)) { res = fillCollection(null, type, itestGenericMap, iTestContext); } else if (Map.class.isAssignableFrom(clazz)) { res = fillMap(null, type, itestGenericMap, iTestContext); } else if (null != requestedClass) { res = generateRandom(requestedClass, itestGenericMap, iTestContext); } else if (type instanceof GenericArrayType) { GenericArrayType arrayType = (GenericArrayType) type; Class<?> componentClass; int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN; if (null != iTestState && iTestState.getSizeParam() != null) { size = iTestState.getSizeParam(); } Map<String, Type> map = new HashMap<String, Type>(itestGenericMap); if (arrayType.getGenericComponentType() instanceof ParameterizedType) { componentClass = (Class<?>) ((ParameterizedType) arrayType.getGenericComponentType()).getRawType(); } else { componentClass = (Class<?>) arrayType.getGenericComponentType(); } Object array = Array.newInstance(componentClass, size); for (int i = 0; i < size; i++) { ITestParamState elementITestState = iTestState == null ? null : iTestState.getElement(String.valueOf(i)); Array.set(array, i, generateRandom(arrayType.getGenericComponentType(), map, iTestContext)); } res = array; } else if (null != iTestState && null == iTestState.getNames()) { res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue()); } else if (clazz.isInterface()) { res = newDynamicProxy(type, itestGenericMap, iTestContext); } else if (type instanceof Class) { res = generateRandom(clazz, itestGenericMap, iTestContext); } else if (Enum.class == clazz) { Type enumType = ITestTypeUtil.getTypeProxy(((ParameterizedType) type).getActualTypeArguments()[0], itestGenericMap); res = generateRandom(enumType, itestGenericMap, iTestContext); } else if (Class.class == clazz) { // probably proxy will be required here res = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { Map<String, Type> map = ITestTypeUtil.getTypeMap(type, itestGenericMap); res = newInstance(clazz, iTestContext, ITestTypeUtil.getTypeActualArguments(type)); fillFields(clazz, res, iTestState, map, iTestContext); } return (T) res; }
From source file:org.pentaho.reporting.engine.classic.core.util.beans.BeanUtility.java
private void updateArrayProperty(final PropertyDescriptor pd, final PropertySpecification name, final Object o) throws BeanException { final Method readMethod = pd.getReadMethod(); if (readMethod == null) { throw new BeanException("Property is not readable, cannot perform array update: " + name); }/*from w ww. j av a 2s .co m*/ try { // System.out.println(readMethod); final Object value = readMethod.invoke(bean); // we have (possibly) an array. final int index = Integer.parseInt(name.getIndex()); final Object array = validateArray(BeanUtility.getPropertyType(pd), value, index); Array.set(array, index, o); final Method writeMethod = pd.getWriteMethod(); writeMethod.invoke(bean, array); } catch (BeanException e) { throw e; } catch (Exception e) { BeanUtility.logger.warn("Failed to read property, cannot perform array update: " + name, e); throw new BeanException("Failed to read property, cannot perform array update: " + name); } }
From source file:com.haulmont.cuba.core.sys.MetadataBuildSupport.java
private Object getXmlAnnotationAttributeValue(Element attributeEl) { String value = attributeEl.attributeValue("value"); String className = attributeEl.attributeValue("class"); String datatypeName = attributeEl.attributeValue("datatype"); List<Element> values = Dom4j.elements(attributeEl, "value"); if (StringUtils.isNotBlank(value)) { if (!values.isEmpty()) throw new IllegalStateException( "Both 'value' attribute and 'value' element(s) are specified for attribute " + attributeEl.attributeValue("name")); return getXmlAnnotationAttributeValue(value, className, datatypeName); }//w w w . jav a 2s . c o m if (!values.isEmpty()) { Object val0 = getXmlAnnotationAttributeValue(values.get(0).getTextTrim(), className, datatypeName); Object array = Array.newInstance(val0.getClass(), values.size()); Array.set(array, 0, val0); for (int i = 1; i < values.size(); i++) { Object val = getXmlAnnotationAttributeValue(values.get(i).getTextTrim(), className, datatypeName); Array.set(array, i, val); } return array; } return null; }
From source file:com.espertech.esper.epl.core.SelectExprInsertEventBeanFactory.java
private static SelectExprProcessor initializeSetterManufactor(EventType eventType, Set<WriteablePropertyDescriptor> writables, boolean isUsingWildcard, StreamTypeService typeService, ExprEvaluator[] expressionNodes, String[] columnNames, Object[] expressionReturnTypes, EngineImportService engineImportService, EventAdapterService eventAdapterService) throws ExprValidationException { List<WriteablePropertyDescriptor> writablePropertiesList = new ArrayList<WriteablePropertyDescriptor>(); List<ExprEvaluator> evaluatorsList = new ArrayList<ExprEvaluator>(); List<TypeWidener> widenersList = new ArrayList<TypeWidener>(); // loop over all columns selected, if any for (int i = 0; i < columnNames.length; i++) { WriteablePropertyDescriptor selectedWritable = null; TypeWidener widener = null;/*from w w w . j av a 2s . c om*/ ExprEvaluator evaluator = expressionNodes[i]; for (WriteablePropertyDescriptor desc : writables) { if (!desc.getPropertyName().equals(columnNames[i])) { continue; } Object columnType = expressionReturnTypes[i]; if (columnType == null) { TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], null, desc.getType(), desc.getPropertyName()); } else if (columnType instanceof EventType) { EventType columnEventType = (EventType) columnType; final Class returnType = columnEventType.getUnderlyingType(); widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], columnEventType.getUnderlyingType(), desc.getType(), desc.getPropertyName()); // handle evaluator returning an event if (JavaClassHelper.isSubclassOrImplementsInterface(returnType, desc.getType())) { selectedWritable = desc; widener = new TypeWidener() { public Object widen(Object input) { if (input instanceof EventBean) { return ((EventBean) input).getUnderlying(); } return input; } }; continue; } // find stream int streamNum = 0; for (int j = 0; j < typeService.getEventTypes().length; j++) { if (typeService.getEventTypes()[j] == columnEventType) { streamNum = j; break; } } final int streamNumEval = streamNum; evaluator = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = eventsPerStream[streamNumEval]; if (theEvent != null) { return theEvent.getUnderlying(); } return null; } public Class getType() { return returnType; } }; } // handle case where the select-clause contains an fragment array else if (columnType instanceof EventType[]) { EventType columnEventType = ((EventType[]) columnType)[0]; final Class componentReturnType = columnEventType.getUnderlyingType(); final Class arrayReturnType = Array.newInstance(componentReturnType, 0).getClass(); widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], arrayReturnType, desc.getType(), desc.getPropertyName()); final ExprEvaluator inner = evaluator; evaluator = 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; } }; } else if (!(columnType instanceof Class)) { String message = "Invalid assignment of column '" + columnNames[i] + "' of type '" + columnType + "' to event property '" + desc.getPropertyName() + "' typed as '" + desc.getType().getName() + "', column and parameter types mismatch"; throw new ExprValidationException(message); } else { widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], (Class) columnType, desc.getType(), desc.getPropertyName()); } selectedWritable = desc; break; } if (selectedWritable == null) { String message = "Column '" + columnNames[i] + "' could not be assigned to any of the properties of the underlying type (missing column names, event property, setter method or constructor?)"; throw new ExprValidationException(message); } // add writablePropertiesList.add(selectedWritable); evaluatorsList.add(evaluator); widenersList.add(widener); } // handle wildcard if (isUsingWildcard) { EventType sourceType = typeService.getEventTypes()[0]; for (EventPropertyDescriptor eventPropDescriptor : sourceType.getPropertyDescriptors()) { if (eventPropDescriptor.isRequiresIndex() || (eventPropDescriptor.isRequiresMapkey())) { continue; } WriteablePropertyDescriptor selectedWritable = null; TypeWidener widener = null; ExprEvaluator evaluator = null; for (WriteablePropertyDescriptor writableDesc : writables) { if (!writableDesc.getPropertyName().equals(eventPropDescriptor.getPropertyName())) { continue; } widener = TypeWidenerFactory.getCheckPropertyAssignType(eventPropDescriptor.getPropertyName(), eventPropDescriptor.getPropertyType(), writableDesc.getType(), writableDesc.getPropertyName()); selectedWritable = writableDesc; final String propertyName = eventPropDescriptor.getPropertyName(); final Class propertyType = eventPropDescriptor.getPropertyType(); evaluator = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = eventsPerStream[0]; if (theEvent != null) { return theEvent.get(propertyName); } return null; } public Class getType() { return propertyType; } }; break; } if (selectedWritable == null) { String message = "Event property '" + eventPropDescriptor.getPropertyName() + "' could not be assigned to any of the properties of the underlying type (missing column names, event property, setter method or constructor?)"; throw new ExprValidationException(message); } writablePropertiesList.add(selectedWritable); evaluatorsList.add(evaluator); widenersList.add(widener); } } // assign WriteablePropertyDescriptor[] writableProperties = writablePropertiesList .toArray(new WriteablePropertyDescriptor[writablePropertiesList.size()]); ExprEvaluator[] exprEvaluators = evaluatorsList.toArray(new ExprEvaluator[evaluatorsList.size()]); TypeWidener[] wideners = widenersList.toArray(new TypeWidener[widenersList.size()]); EventBeanManufacturer eventManufacturer; try { eventManufacturer = eventAdapterService.getManufacturer(eventType, writableProperties, engineImportService, false); } catch (EventBeanManufactureException e) { throw new ExprValidationException(e.getMessage(), e); } return new SelectExprInsertNativeWidening(eventType, eventManufacturer, exprEvaluators, wideners); }
From source file:net.kemuri9.sling.filesystemprovider.impl.PersistenceHelper.java
/** * Create a property value usable in the ValueMap system * @param path the resource path (in the repository, not on disk) * @param property JSON property to read into data * @return java object matching the JSON property data. */// w w w . j a v a 2s. c o m private static Object readJSONPropertyValue(String path, JSONObject property) { String type = property.optString(FSPConstants.JSON_KEY_TYPE); JSONArray values = property.optJSONArray(FSPConstants.JSON_KEY_VALUES); Object value = property.opt(FSPConstants.JSON_KEY_VALUE); boolean isBinary = property.optBoolean(FSPConstants.JSON_KEY_BINARY, false); Class<?> clazz = Util.loadClass(type); if (clazz == null) { return null; } if (values == null) { // single value case Object valToConvert = readBinary(path, deNull(value), isBinary); return ValueConversion.convert(valToConvert, clazz); } else { // multi-value case Object vals = Array.newInstance(clazz, values.length()); for (int valIdx = 0; valIdx < values.length(); ++valIdx) { // use opt instead of get to avoid the JSONException Object val = readBinary(path, deNull(values.opt(valIdx)), isBinary); Array.set(vals, valIdx, ValueConversion.convert(val, clazz)); } return vals; } }
From source file:com.azure.webapi.MobileServiceClient.java
/** * Invokes a custom API/*from w w w . j ava2 s . c o m*/ * * @param apiName * The API name * @param body * The object to send as the request body * @param httpMethod * The HTTP Method used to invoke the API * @param parameters * The query string parameters sent in the request * @param clazz * The API result class * @param callback * The callback to invoke after the API execution */ public <E> void invokeApi(String apiName, Object body, String httpMethod, List<Pair<String, String>> parameters, final Class<E> clazz, final ApiOperationCallback<E> callback) { if (clazz == null) { if (callback != null) { callback.onCompleted(null, new IllegalArgumentException("clazz cannot be null"), null); } return; } JsonElement json = null; if (body != null) { json = getGsonBuilder().create().toJsonTree(body); } invokeApi(apiName, json, httpMethod, parameters, new ApiJsonOperationCallback() { @SuppressWarnings("unchecked") @Override public void onCompleted(JsonElement jsonElement, Exception exception, ServiceFilterResponse response) { if (callback != null) { if (exception == null) { Class<?> concreteClass = clazz; if (clazz.isArray()) { concreteClass = clazz.getComponentType(); } List<?> entities = JsonEntityParser.parseResults(jsonElement, getGsonBuilder().create(), concreteClass); if (clazz.isArray()) { E array = (E) Array.newInstance(concreteClass, entities.size()); for (int i = 0; i < entities.size(); i++) { Array.set(array, i, entities.get(i)); } callback.onCompleted(array, null, response); } else { callback.onCompleted((E) entities.get(0), exception, response); } } else { callback.onCompleted(null, exception, response); } } } }); }
From source file:org.jaxygen.converters.properties.PropertiesToBeanConverter.java
private static Object resizeArray(Object array, int size) { Object newArray = Array.newInstance(array.getClass().getComponentType(), size); for (int i = 0; i < Array.getLength(array); i++) { Object value = Array.get(array, i); Array.set(newArray, i, value); }/* ww w .j a v a 2s .c o m*/ return newArray; }
From source file:com.jaspersoft.jasperserver.export.modules.common.DefaultReportParametersTranslator.java
protected Object toArrayValue(Class valueClass, Object[] beanValue) { Class componentType = valueClass.getComponentType(); Object value;/* www.ja v a2 s . com*/ if (beanValue == null) { value = Array.newInstance(componentType, 0); } else { value = Array.newInstance(componentType, beanValue.length); for (int i = 0; i < beanValue.length; i++) { Array.set(value, i, toValue(beanValue[i])); } } return value; }