Java Code Examples for java.lang.reflect.Array#set()

The following examples show how to use java.lang.reflect.Array#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PrimitiveConverter.java    From bitchat with Apache License 2.0 6 votes vote down vote up
/**
 * 对基本类型进行类型转换
 */
@Override
@SuppressWarnings("unused")
protected Object doConvertValue(Object source, Class<?> toType, Object... params) {
    /*
     * 如果是基础类型,则直接返回
     */
    if (source != null && (!PrimitiveTypeUtil.isPriType(source.getClass()) || !PrimitiveTypeUtil.isPriType(toType))) {
        return null;
    }

    /*
     * 如果都是数组类型,则构造数组
     */
    if (source != null && source.getClass().isArray() && toType.isArray()) {
        Object result;
        Class<?> componentType = toType.getComponentType();
        result = Array.newInstance(componentType, Array.getLength(source));

        for (int i = 0; i < Array.getLength(source); i++) {
            Array.set(result, i, convert(Array.get(source, i), componentType, params));
        }
        return result;
    }
    return doConvert(source, toType);
}
 
Example 2
Source File: AbstractNestablePropertyAccessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Object growArrayIfNecessary(Object array, int index, String name) {
	if (!isAutoGrowNestedPaths()) {
		return array;
	}
	int length = Array.getLength(array);
	if (index >= length && index < this.autoGrowCollectionLimit) {
		Class<?> componentType = array.getClass().getComponentType();
		Object newArray = Array.newInstance(componentType, index + 1);
		System.arraycopy(array, 0, newArray, 0, length);
		for (int i = length; i < Array.getLength(newArray); i++) {
			Array.set(newArray, i, newValue(componentType, null, name));
		}
		setPropertyValue(name, newArray);
		Object defaultValue = getPropertyValue(name);
		Assert.state(defaultValue != null, "Default value must not be null");
		return defaultValue;
	}
	else {
		return array;
	}
}
 
Example 3
Source File: CollectionToArrayConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Collection<?> sourceCollection = (Collection<?>) source;
	TypeDescriptor targetElementType = targetType.getElementTypeDescriptor();
	Assert.state(targetElementType != null, "No target element type");
	Object array = Array.newInstance(targetElementType.getType(), sourceCollection.size());
	int i = 0;
	for (Object sourceElement : sourceCollection) {
		Object targetElement = this.conversionService.convert(sourceElement,
				sourceType.elementTypeDescriptor(sourceElement), targetElementType);
		Array.set(array, i++, targetElement);
	}
	return array;
}
 
Example 4
Source File: OperationFactory.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public Object operate( Object value )
{
    StringTokenizer st = new StringTokenizer( getString( value ),
        sep ) ;
    int length = st.countTokens() ;
    Object result = null ;
    int ctr = 0 ;
    while (st.hasMoreTokens()) {
        String next = st.nextToken() ;
        Object val = act.operate( next ) ;
        if (result == null)
            result = Array.newInstance( val.getClass(), length ) ;
        Array.set( result, ctr++, val ) ;
    }

    return result ;
}
 
Example 5
Source File: ArrayUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Underlying implementation of add(array, index, element) methods. 
 * The last parameter is the class, which may not equal element.getClass 
 * for primitives.
 *
 * @param array  the array to add the element to, may be <code>null</code>
 * @param index  the position of the new object
 * @param element  the object to add
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(Object array, int index, Object element, Class clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    Object result = Array.newInstance(clss, length + 1);
    System.arraycopy(array, 0, result, 0, index);
    Array.set(result, index, element);
    if (index < length) {
        System.arraycopy(array, index, result, index + 1, length - index);
    }
    return result;
}
 
Example 6
Source File: Helper.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Object randomArg(Class<?> param) {
    Object wrap = castToWrapperOrNull(nextArg(param), param);
    if (wrap != null) {
        return wrap;
    }

    if (param.isInterface()) {
        for (Class<?> c : param.getClasses()) {
            if (param.isAssignableFrom(c) && !c.isInterface()) {
                param = c;
                break;
            }
        }
    }
    if (param.isArray()) {
        Class<?> ctype = param.getComponentType();
        Object arg = Array.newInstance(ctype, 2);
        Array.set(arg, 0, randomArg(ctype));
        return arg;
    }
    if (param.isInterface() && param.isAssignableFrom(List.class)) {
        return Arrays.asList("#" + nextArg());
    }
    if (param.isInterface() || param.isAssignableFrom(String.class)) {
        return "#" + nextArg();
    }

    try {
        return param.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
    }
    return null;  // random class not Object, String, Integer, etc.
}
 
Example 7
Source File: AnnotationValue.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public U[] resolve() {
    @SuppressWarnings("unchecked")
    U[] resolved = (U[]) Array.newInstance(unloadedComponentType, values.size());
    int index = 0;
    for (AnnotationValue<?, ?> value : values) {
        Array.set(resolved, index++, value.resolve());
    }
    return resolved;
}
 
Example 8
Source File: ConversionUtil.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T[] toArray(List<T> list, Class<T> c) {
    Object array = Array.newInstance(c, list.size());
    for (int i = 0; i < list.size(); i++) {
        Array.set(array, i, list.get(i));
    }
    return (T[]) array;
}
 
Example 9
Source File: PartitionedRemoteServiceMethod.java    From astrix with Apache License 2.0 5 votes vote down vote up
@Override
Object buildTarget() {
	Object array = Array.newInstance(elementType, elements.size());
	int nextIndex = 0;
	for (Object element : elements) {
		Array.set(array, nextIndex, element);
		nextIndex++;
	}
	return array;
}
 
Example 10
Source File: SqlgUtil.java    From sqlg with MIT License 5 votes vote down vote up
public static Integer[] convertObjectOfIntegersArrayToIntegerArray(Object[] integerArray) {
    Integer[] target = new Integer[integerArray.length];
    for (int i = 0; i < integerArray.length; i++) {
        Array.set(target, i, integerArray[i]);
    }
    return target;
}
 
Example 11
Source File: AnnotationProxyMaker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void visitArray(Attribute.Array a) {
    Name elemName = ((ArrayType) a.type).elemtype.tsym.getQualifiedName();

    if (elemName.equals(elemName.table.names.java_lang_Class)) {   // Class[]
        // Construct a proxy for a MirroredTypesException
        ListBuffer<TypeMirror> elems = new ListBuffer<>();
        for (Attribute value : a.values) {
            Type elem = ((Attribute.Class) value).classType;
            elems.append(elem);
        }
        value = new MirroredTypesExceptionProxy(elems.toList());

    } else {
        int len = a.values.length;
        Class<?> returnClassSaved = returnClass;
        returnClass = returnClass.getComponentType();
        try {
            Object res = Array.newInstance(returnClass, len);
            for (int i = 0; i < len; i++) {
                a.values[i].accept(this);
                if (value == null || value instanceof ExceptionProxy) {
                    return;
                }
                try {
                    Array.set(res, i, value);
                } catch (IllegalArgumentException e) {
                    value = null;       // indicates a type mismatch
                    return;
                }
            }
            value = res;
        } finally {
            returnClass = returnClassSaved;
        }
    }
}
 
Example 12
Source File: Helper.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static Object randomArg(Class<?> param) {
    Object wrap = castToWrapperOrNull(nextArg(param), param);
    if (wrap != null) {
        return wrap;
    }

    if (param.isInterface()) {
        for (Class<?> c : param.getClasses()) {
            if (param.isAssignableFrom(c) && !c.isInterface()) {
                param = c;
                break;
            }
        }
    }
    if (param.isArray()) {
        Class<?> ctype = param.getComponentType();
        Object arg = Array.newInstance(ctype, 2);
        Array.set(arg, 0, randomArg(ctype));
        return arg;
    }
    if (param.isInterface() && param.isAssignableFrom(List.class)) {
        return Arrays.asList("#" + nextArg());
    }
    if (param.isInterface() || param.isAssignableFrom(String.class)) {
        return "#" + nextArg();
    }

    try {
        return param.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
    }
    return null;  // random class not Object, String, Integer, etc.
}
 
Example 13
Source File: PropertyElementHandler.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the search of the setter for the property
 * with specified {@code name} in specified class
 * and updates value of the property.
 *
 * @param bean   the context bean that contains property
 * @param name   the name of the property
 * @param index  the index of the indexed property
 * @param value  the new value for the property
 * @throws IllegalAccessException    if the property is not accesible
 * @throws IntrospectionException    if the bean introspection is failed
 * @throws InvocationTargetException if the setter cannot be invoked
 * @throws NoSuchMethodException     if the setter is not found
 */
private static void setPropertyValue(Object bean, String name, Integer index, Object value) throws IllegalAccessException, IntrospectionException, InvocationTargetException, NoSuchMethodException {
    Class<?> type = bean.getClass();
    Class<?> param = (value != null)
            ? value.getClass()
            : null;

    if (index == null) {
        MethodUtil.invoke(findSetter(type, name, param), bean, new Object[] {value});
    } else if (type.isArray() && (name == null)) {
        Array.set(bean, index, value);
    } else {
        MethodUtil.invoke(findSetter(type, name, int.class, param), bean, new Object[] {index, value});
    }
}
 
Example 14
Source File: Java9ModuleInitializer.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Object moduleFinderOf(List<File> files) {
  Object paths = Array.newInstance(java_nio_file_Path, files.size());
  for (int i = 0; i < files.size(); i++) {
    File file = files.get(i);

    Array.set(paths, i, instanceInvoke(java_io_File_toPath, file));
  }

  return staticInvoke(java_lang_module_ModuleFinder_of, paths);
}
 
Example 15
Source File: StringToArrayConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	String string = (String) source;
	String[] fields = StringUtils.commaDelimitedListToStringArray(string);
	Object target = Array.newInstance(targetType.getElementTypeDescriptor().getType(), fields.length);
	for (int i = 0; i < fields.length; i++) {
		String sourceElement = fields[i];
		Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, targetType.getElementTypeDescriptor());
		Array.set(target, i, targetElement);
	}
	return target;
}
 
Example 16
Source File: HprofHeapObjectReader.java    From leakcanary-for-eclipse with MIT License 4 votes vote down vote up
private Object convert(PrimitiveArrayImpl array, byte[] content)
{
    if (array.getType() == IObject.Type.BYTE)
        return content;

    int elementSize = IPrimitiveArray.ELEMENT_SIZE[array.getType()];
    int length = content.length / elementSize;

    Object answer = Array.newInstance(IPrimitiveArray.COMPONENT_TYPE[array.getType()], length);

    int index = 0;
    for (int ii = 0; ii < content.length; ii += elementSize)
    {
        switch (array.getType())
        {
            case IObject.Type.BOOLEAN:
                Array.set(answer, index, content[ii] != 0);
                break;
            case IObject.Type.CHAR:
                Array.set(answer, index, readChar(content, ii));
                break;
            case IObject.Type.FLOAT:
                Array.set(answer, index, readFloat(content, ii));
                break;
            case IObject.Type.DOUBLE:
                Array.set(answer, index, readDouble(content, ii));
                break;
            case IObject.Type.SHORT:
                Array.set(answer, index, readShort(content, ii));
                break;
            case IObject.Type.INT:
                Array.set(answer, index, readInt(content, ii));
                break;
            case IObject.Type.LONG:
                Array.set(answer, index, readLong(content, ii));
                break;
        }

        index++;
    }

    return answer;
}
 
Example 17
Source File: FieldAccessor.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override
public T set(T record, F fieldValue) {
	Array.set(record, pos, fieldValue);
	return record;
}
 
Example 18
Source File: RainbowMath.java    From rainbow with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static Object append(Object b, final Object value) {
    final int length = Array.getLength(b);
    b = RainbowMath.expand(b, length + 1);
    Array.set(b, length, value);
    return b;
}
 
Example 19
Source File: CollectionAndCollectionConvertor.java    From tddl with Apache License 2.0 4 votes vote down vote up
protected void arraySet(Object src, Class compoentType, int i, Object value) {
    Array.set(src, i, value);
}
 
Example 20
Source File: ArrayELResolver.java    From flowable-engine with Apache License 2.0 3 votes vote down vote up
/**
 * If the base object is a Java language array, attempts to set the value at the given index
 * with the given value. The index is specified by the property argument, and coerced into an
 * integer. If the coercion could not be performed, an IllegalArgumentException is thrown. If
 * the index is out of bounds, a PropertyNotFoundException is thrown. If the base is a Java
 * language array, the propertyResolved property of the ELContext object must be set to true by
 * this resolver, before returning. If this property is not true after this method is called,
 * the caller can safely assume no value was set. If this resolver was constructed in read-only
 * mode, this method will always throw PropertyNotWritableException.
 * 
 * @param context
 *            The context of this evaluation.
 * @param base
 *            The array to analyze. Only bases that are a Java language array are handled by
 *            this resolver.
 * @param property
 *            The index of the element in the array to return the acceptable type for. Will be
 *            coerced into an integer, but otherwise ignored by this resolver.
 * @param value
 *            The value to be set at the given index.
 * @throws PropertyNotFoundException
 *             if the given index is out of bounds for this array.
 * @throws ClassCastException
 *             if the class of the specified element prevents it from being added to this array.
 * @throws NullPointerException
 *             if context is null
 * @throws IllegalArgumentException
 *             if the property could not be coerced into an integer, or if some aspect of the
 *             specified element prevents it from being added to this array.
 * @throws PropertyNotWritableException
 *             if this resolver was constructed in read-only mode.
 * @throws ELException
 *             if an exception was thrown while performing the property or variable resolution.
 *             The thrown exception must be included as the cause property of this exception, if
 *             available.
 */
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
	if (context == null) {
		throw new NullPointerException("context is null");
	}
	if (isResolvable(base)) {
		if (readOnly) {
			throw new PropertyNotWritableException("resolver is read-only");
		}
		Array.set(base, toIndex(base, property), value);
		context.setPropertyResolved(true);
	}
}