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:org.jaxygen.converters.properties.PropertiesToBeanConverter.java
private static void fillBeanArrayField(final String name, Object value, Object bean, BeanInfo beanInfo, String[] path, final String fieldName, int bracketStart, int len) throws IllegalAccessException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalArgumentException, WrongProperyIndex { final String indexStr = fieldName.substring(bracketStart + 1, len - 1); final String propertyName = fieldName.substring(0, bracketStart); int index = Integer.parseInt(indexStr); String childName = ""; int firstDot = name.indexOf("."); if (firstDot > 0) { childName = name.substring(firstDot + 1); }/*from w w w . j av a 2s. c om*/ for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if (pd.getName().equals(propertyName)) { Method writter = pd.getWriteMethod(); Method reader = pd.getReadMethod(); if (writter != null && reader != null) { Object array = reader.invoke(bean); if (pd.getPropertyType().isArray()) { if (array == null) { array = Array.newInstance(pd.getPropertyType().getComponentType(), index + 1); writter.invoke(bean, array); } if (Array.getLength(array) < (index + 1)) { array = resizeArray(array, index + 1); writter.invoke(bean, array); } if (path.length == 1) { Object valueObject = parsePropertyToValue(value, array.getClass().getComponentType()); Array.set(array, index, valueObject); } else { Object valueObject = fillBeanValueByName(childName, value, array.getClass().getComponentType(), Array.get(array, index)); Array.set(array, index, valueObject); } } else if (pd.getPropertyType().equals(List.class)) { if (array == null) { array = pd.getPropertyType().newInstance(); writter.invoke(bean, array); } Class<?> genericClass = array.getClass().getTypeParameters()[0].getClass(); if (path.length == 1) { Object valueObject = parsePropertyToValue(value, genericClass); Array.set(array, index, valueObject); } else { Object valueObject = fillBeanValueByName(childName, value, genericClass, null); Array.set(array, index, valueObject); } } } } } }
From source file:com.espertech.esper.event.xml.XPathPropertyGetter.java
private Object castToArray(Object result) { if (!(result instanceof NodeList)) { return null; }/*from w w w. jav a2 s .c o m*/ NodeList nodeList = (NodeList) result; Object array = Array.newInstance(optionalCastToType, nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Object arrayItem = null; try { Node item = nodeList.item(i); String textContent; if ((item.getNodeType() == Node.ATTRIBUTE_NODE) || (item.getNodeType() == Node.ELEMENT_NODE)) { textContent = nodeList.item(i).getTextContent(); } else { continue; } arrayItem = simpleTypeParser.parse(textContent); } catch (Exception ex) { if (log.isInfoEnabled()) { log.info("Parse error for text content " + nodeList.item(i).getTextContent() + " for expression " + expression); } } Array.set(array, i, arrayItem); } return array; }
From source file:com.vk.sdk.api.model.ParseUtils.java
/** * Parses array from given JSONArray./*w w w .ja v a2s .co m*/ * Supports parsing of primitive types and {@link com.vk.sdk.api.model.VKApiModel} instances. * @param array JSONArray to parse * @param arrayClass type of array field in class. * @return object to set to array field in class * @throws JSONException if given array have incompatible type with given field. */ private static Object parseArrayViaReflection(JSONArray array, Class arrayClass) throws JSONException { Object result = Array.newInstance(arrayClass.getComponentType(), array.length()); Class<?> subType = arrayClass.getComponentType(); for (int i = 0; i < array.length(); i++) { try { Object item = array.opt(i); if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) { VKApiModel model = (VKApiModel) subType.newInstance(); item = model.parse((JSONObject) item); } Array.set(result, i, item); } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (IllegalArgumentException e) { throw new JSONException(e.getMessage()); } } return result; }
From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java
protected Object provideArrayValue(Member member, TypeLiteral<?> type, Class<?> memberType, Predicate<Binding> filter) { Class<?> componentType = memberType.getComponentType(); Set<Binding<?>> set = getSortedBindings(componentType, filter); // TODO should we return an empty array when no matches? // FWIW Spring seems to return null if (set.isEmpty()) { return null; }/*w w w . j ava2 s . com*/ Object array = Array.newInstance(componentType, set.size()); int index = 0; for (Binding<?> binding : set) { Object value = binding.getProvider().get(); Array.set(array, index++, value); } return array; }
From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java
/** * {@inheritDoc}/*from w w w . j a va2 s . co m*/ */ @Override public Object convertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { if (!(value instanceof NativeArray)) { throw new IllegalArgumentException("value must be a NativeArray"); } final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); final Object result; if (expectedClass.isAssignableFrom(List.class) || expectedClass.isArray()) { final Class<?> expectedComponentClass = expectedClass.isArray() ? expectedClass.getComponentType() : Object.class; final List<Object> list = new ArrayList<Object>(); for (int idx = 0; idx < ids.length; idx++) { if (ids[idx] instanceof Integer) { final Object element = arr.get(((Integer) ids[idx]).intValue(), arr); final Object converted = globalDelegate.convertValueForJava(element, expectedComponentClass); list.add(converted); } } if (expectedClass.isArray()) { final Object newArr = Array.newInstance(expectedComponentClass, list.size()); for (int idx = 0; idx < list.size(); idx++) { Array.set(newArr, idx, list.get(idx)); } result = newArr; } else { result = list; } } else { final Map<Object, Object> propValues = new HashMap<Object, Object>(ids.length); for (final Object propId : ids) { final Object val = arr.get(propId.toString(), arr); final Object convertedKey = globalDelegate.convertValueForJava(propId); final Object convertedValue = globalDelegate.convertValueForJava(val); propValues.put(convertedKey, convertedValue); } result = propValues; } return result; }
From source file:org.jolokia.converter.object.StringToObjectConverter.java
private Object convertToArray(String pType, String pValue) { // It's an array String t = pType.substring(1, 2); Class valueType;//from ww w .jav a2 s . c om if (t.equals("L")) { // It's an object-type String oType = pType.substring(2, pType.length() - 1).replace('/', '.'); valueType = ClassUtil.classForName(oType); if (valueType == null) { throw new IllegalArgumentException("No class of type " + oType + "found"); } } else { valueType = TYPE_SIGNATURE_MAP.get(t); if (valueType == null) { throw new IllegalArgumentException("Cannot convert to unknown array type " + t); } } String[] values = EscapeUtil.splitAsArray(pValue, EscapeUtil.PATH_ESCAPE, ","); Object ret = Array.newInstance(valueType, values.length); int i = 0; for (String value : values) { Array.set(ret, i++, value.equals("[null]") ? null : convertFromString(valueType.getCanonicalName(), value)); } return ret; }
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 w w . j av a 2 s . com*/ 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() + ")"); } }
From source file:com.espertech.esper.epl.annotation.AnnotationUtil.java
private static Object getFinalValue(Class annotationClass, AnnotationAttribute annotationAttribute, Object value, EngineImportService engineImportService) throws AnnotationException { if (value == null) { if (annotationAttribute.getDefaultValue() == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a value for attribute '" + annotationAttribute.getName() + "'"); }/*from w w w . j ava 2s . c o m*/ return annotationAttribute.getDefaultValue(); } // handle non-array if (!annotationAttribute.getType().isArray()) { // handle primitive value if (!annotationAttribute.getType().isAnnotation()) { SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(value.getClass(), annotationAttribute.getType()); Object finalValue = caster.cast(value); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return finalValue; } else { // nested annotation if (!(value instanceof AnnotationDesc)) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return createProxy((AnnotationDesc) value, engineImportService); } } if (!value.getClass().isArray()) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } Object array = Array.newInstance(annotationAttribute.getType().getComponentType(), Array.getLength(value)); for (int i = 0; i < Array.getLength(value); i++) { Object arrayValue = Array.get(value, i); if (arrayValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + "non-null value for array elements for attribute '" + annotationAttribute.getName() + "'"); } SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(arrayValue.getClass(), annotationAttribute.getType().getComponentType()); Object finalValue = caster.cast(arrayValue); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getComponentType().getSimpleName() + "-typed value for array elements for attribute '" + annotationAttribute.getName() + "' but received " + "a " + arrayValue.getClass().getSimpleName() + "-typed value"); } Array.set(array, i, finalValue); } return array; }
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 va 2 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;// w w w. j a v a 2 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; } 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); } }