Example usage for java.lang.reflect Array set

List of usage examples for java.lang.reflect Array set

Introduction

In this page you can find the example usage for java.lang.reflect Array set.

Prototype

public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Sets the value of the indexed component of the specified array object to the specified new value.

Usage

From source file:com.adf.bean.AbsBean.java

/**
 * IMPORT/*  w  ww. j  a  v  a  2  s .  c o m*/
 * */
private void setArrayColumn(String col, JSONArray arr)
        throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
    Field f;
    f = getClass().getDeclaredField(col);
    f.setAccessible(true);
    Class<?> arrCls = f.getType();
    Class<?> objCls = getArrayObjectClass(arrCls);
    if (objCls != null) {
        Object array = Array.newInstance(objCls, arr.length());
        for (int i = 0; i < arr.length(); i++) {
            Object oi = arr.opt(i);
            if (oi.getClass() == objCls) {
                Array.set(array, i, arr.opt(i));
            } else {
                Constructor<?> cons;
                try {
                    cons = objCls.getDeclaredConstructor(String.class);
                    cons.setAccessible(true);
                    Object obj = cons.newInstance(oi.toString());
                    Array.set(array, i, obj);
                } catch (NoSuchMethodException e) {
                    LogUtil.err("setArrayColumn NoSuchMethodException, col " + col + " :" + e.getMessage());
                } catch (InstantiationException e) {
                    LogUtil.err("setArrayColumn InstantiationException, col " + col + " :" + e.getMessage());
                } catch (InvocationTargetException e) {
                    LogUtil.err("setArrayColumn InvocationTargetException, col " + col + " :" + e.getMessage());
                }
            }
        }
        f.set(this, array);
    } else {
        throw new IllegalArgumentException("Can not get Array Column Object class");
    }
}

From source file:de.alpharogroup.lang.object.CloneObjectExtensions.java

/**
 * Try to clone the given object./*from  w  w w  . ja va  2s  .  c o m*/
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             Thrown if a matching method is not found or if the name is "&lt;init&gt;"or
 *             "&lt;clinit&gt;".
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             Thrown if this {@code Method} object is enforcing Java language access control
 *             and the underlying method is inaccessible.
 * @throws IllegalArgumentException
 *             Thrown if an illegal argument is given
 * @throws InvocationTargetException
 *             Thrown if the property accessor method throws an exception
 * @throws ClassNotFoundException
 *             occurs if a given class cannot be located by the specified class loader
 * @throws InstantiationException
 *             Thrown if one of the following reasons: the class object
 *             <ul>
 *             <li>represents an abstract class</li>
 *             <li>represents an interface</li>
 *             <li>represents an array class</li>
 *             <li>represents a primitive type</li>
 *             <li>represents {@code void}</li>
 *             <li>has no nullary constructor</li>
 *             </ul>
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectExtensions.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionExtensions.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:org.apache.axis.utils.BeanPropertyDescriptor.java

/**
 * Set an indexed property value/*from w w  w  . j a v  a 2s  . c  om*/
 * @param obj is the object
 * @param i the index
 * @param newValue is the new value
 */
public void set(Object obj, int i, Object newValue) throws InvocationTargetException, IllegalAccessException {
    // Set the new value
    if (isIndexed()) {
        IndexedPropertyDescriptor id = (IndexedPropertyDescriptor) myPD;
        growArrayToSize(obj, id.getIndexedPropertyType(), i);
        id.getIndexedWriteMethod().invoke(obj, new Object[] { new Integer(i), newValue });
    } else {
        // Not calling 'growArrayToSize' to avoid an extra call to the
        // property's setter. The setter will be called at the end anyway.
        // growArrayToSize(obj, myPD.getPropertyType().getComponentType(), i);
        Object array = get(obj);
        if (array == null || Array.getLength(array) <= i) {
            Class componentType = getType().getComponentType();
            Object newArray = Array.newInstance(componentType, i + 1);
            // Copy over the old elements
            if (array != null) {
                System.arraycopy(array, 0, newArray, 0, Array.getLength(array));
            }
            array = newArray;
        }
        Array.set(array, i, newValue);
        // Fix for non-indempondent array-type propertirs.
        // Make sure we call the property's setter.
        set(obj, array);
    }
}

From source file:org.junitext.runners.parameters.factory.SetPropertyWithParameterRule.java

/**
 * Converts the given list to an array of the given component type. This
 * utility method can even convert multi-dimensional arrays.
 * /*from w ww. ja  va 2  s  .c o m*/
 * @param parameterAsList
 *            the <code>List</code> to convert to an array
 * @param componentType
 *            specifies the type of array to create
 * @return
 */
private Object listToArray(List<?> listToConvert, Class<?> componentType) {
    // This is a tricky bit of Java reflection. Basically, it is not
    // possible to use the List.toArray(T[]) method because the type of the
    // array is not known at compile time. Instead, we need to create a
    // brand new instance of the array with the given component type of the
    // same size as the list. Then all we need to do is to copy the list
    // elements into the array.
    Object newArray = Array.newInstance(componentType, listToConvert.size());
    for (int j = 0; j < listToConvert.size(); j++) {
        Object arrayElement = listToConvert.get(j);
        if (componentType.isArray()) {
            // We are dealing with a multi-dimensional array. Use recusion
            // to convert each element into an array.
            arrayElement = listToArray((List) arrayElement, componentType.getComponentType());
        }
        Array.set(newArray, j, arrayElement);
    }
    return newArray;
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

@SuppressWarnings("unchecked")
public <T> T generateRandom(Class<T> clazz, Map<String, Type> itestGenericMap, ITestContext iTestContext) {
    Object res;/*w  w  w  .ja v a 2s  .  com*/
    ITestParamState iTestState = iTestContext.getCurrentParam();
    if (null != iTestState && null == iTestState.getNames()) {
        res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue());
    } else if (Void.class == clazz || void.class == clazz) {
        res = null;
    } else if (String.class == clazz && (null == iTestState || null == iTestState.getNames())) {
        res = RandomStringUtils.randomAlphanumeric(20);
    } else if (Long.class == clazz || long.class == clazz) {
        res = new Long(random.nextLong());
    } else if (Integer.class == clazz || int.class == clazz) {
        res = new Integer(random.nextInt());
    } else if (Boolean.class == clazz || boolean.class == clazz) {
        res = random.nextBoolean() ? Boolean.TRUE : Boolean.FALSE;
    } else if (Date.class == clazz) {
        res = new Date(random.nextLong());
    } else if (Double.class == clazz || double.class == clazz) {
        res = random.nextDouble();
    } else if (Float.class == clazz || float.class == clazz) {
        res = random.nextFloat();
    } else if (Character.class == clazz || char.class == clazz) {
        res = RandomStringUtils.random(1).charAt(0);
    } else if (clazz.isEnum()) {
        res = clazz.getEnumConstants()[random.nextInt(clazz.getEnumConstants().length)];
    } else if (clazz.isArray()) {
        int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN;
        if (null != iTestState && iTestState.getSizeParam() != null) {
            size = iTestState.getSizeParam();
        }
        Object array = Array.newInstance(clazz.getComponentType(), size);
        for (int i = 0; i < size; i++) {
            iTestContext.enter(array, String.valueOf(i));
            ITestParamState elementITestState = iTestState == null ? null
                    : iTestState.getElement(String.valueOf(i));
            Object value = generateRandom((Type) clazz.getComponentType(), itestGenericMap, iTestContext);
            Array.set(array, i, value);
            iTestContext.leave(value);
        }
        res = array;
    } else {
        res = newInstance(clazz, iTestContext);
        fillFields(clazz, res, iTestState, Collections.EMPTY_MAP, iTestContext);
    }
    return (T) res;
}

From source file:org.zlogic.vogon.web.TomcatConfigurer.java

/**
 * Configures SSL for Tomcat container/*from   w w w. ja  v  a 2s.  c o  m*/
 *
 * @param container ConfigurableEmbeddedServletContainer instance to
 * configure
 */
private void configureSSL(ConfigurableEmbeddedServletContainer container) {
    if (serverTypeDetector.getKeystoreFile().isEmpty() || serverTypeDetector.getKeystorePassword().isEmpty()) {
        log.debug(messages.getString("KEYSTORE_FILE_OR_PASSWORD_NOT_DEFINED"));
        return;
    }

    log.info(MessageFormat.format(messages.getString("USING_KEYSTORE_WITH_PASSWORD"),
            new Object[] { serverTypeDetector.getKeystoreFile(),
                    serverTypeDetector.getKeystorePassword().replaceAll(".{1}", "*") })); //NOI18N
    Object connector;
    Class connectorClass = null;
    try {
        log.debug(messages.getString("CONFIGURING_CONNECTOR"));
        connectorClass = getClass().getClassLoader().loadClass("org.apache.catalina.connector.Connector"); //NOI18N
        connector = connectorClass.newInstance();
        connectorClass.getMethod("setPort", Integer.TYPE).invoke(connector, 8443); //NOI18N
        connectorClass.getMethod("setSecure", Boolean.TYPE).invoke(connector, true); //NOI18N
        connectorClass.getMethod("setScheme", String.class).invoke(connector, "https"); //NOI18N
        connectorClass.getMethod("setURIEncoding", String.class).invoke(connector, utf8Charset.name()); //NOI18N
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
            | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
        throw new RuntimeException(messages.getString("CANNOT_CONFIGURE_CONNECTOR"), ex);
    }

    Object proto;
    try {
        log.debug(messages.getString("CONFIGURING_PROTOCOLHANDLER_PARAMETERS"));
        proto = connectorClass.getMethod("getProtocolHandler").invoke(connector); //NOI18N
        Class protoClass = proto.getClass();
        log.debug(java.text.MessageFormat.format(messages.getString("CONFIGURING_PROTOCOLHANDLER_CLASS"),
                new Object[] { protoClass.getCanonicalName() }));
        protoClass.getMethod("setSSLEnabled", Boolean.TYPE).invoke(proto, true); //NOI18N
        protoClass.getMethod("setKeystorePass", String.class).invoke(proto,
                serverTypeDetector.getKeystorePassword()); //NOI18N
        protoClass.getMethod("setKeystoreType", String.class).invoke(proto, "JKS"); //NOI18N
        protoClass.getMethod("setKeyAlias", String.class).invoke(proto, "vogonkey"); //NOI18N
        protoClass.getMethod("setKeystoreFile", String.class).invoke(proto,
                new File(serverTypeDetector.getKeystoreFile()).getAbsolutePath()); //NOI18N
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new RuntimeException(messages.getString("CANNOT_CONFIGURE_PROTOCOLHANDLER"), ex);
    }

    try {
        log.debug(messages.getString("ADDING_CONNECTOR_TO_TOMCATEMBEDDEDSERVLETCONTAINERFACTORY"));
        Object connectors = Array.newInstance(connectorClass, 1);
        Array.set(connectors, 0, connector);
        container.getClass().getMethod("addAdditionalTomcatConnectors", connectors.getClass()).invoke(container,
                connectors); //NOI18N
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new RuntimeException(
                messages.getString("CANNOT_ADD_CONNECTOR_TO_TOMCATEMBEDDEDSERVLETCONTAINERFACTORY"), ex);
    }
}

From source file:org.red5.io.utils.ConversionUtils.java

/**
 * Convert to array/*from  w ww. j a  v  a2 s .c om*/
 * 
 * @param source
 *            Source object
 * @param target
 *            Target class
 * @return Converted object
 * @throws ConversionException
 *             If object can't be converted
 */
public static Object convertToArray(Object source, Class<?> target) throws ConversionException {
    try {
        Class<?> targetType = target.getComponentType();
        if (source.getClass().isArray()) {
            Object targetInstance = Array.newInstance(targetType, Array.getLength(source));
            for (int i = 0; i < Array.getLength(source); i++) {
                Array.set(targetInstance, i, convert(Array.get(source, i), targetType));
            }
            return targetInstance;
        }
        if (source instanceof Collection<?>) {
            Collection<?> sourceCollection = (Collection<?>) source;
            Object targetInstance = Array.newInstance(target.getComponentType(), sourceCollection.size());
            Iterator<?> it = sourceCollection.iterator();
            int i = 0;
            while (it.hasNext()) {
                Array.set(targetInstance, i++, convert(it.next(), targetType));
            }
            return targetInstance;
        }
        throw new ConversionException("Unable to convert to array");
    } catch (Exception ex) {
        throw new ConversionException("Error converting to array", ex);
    }
}

From source file:org.deephacks.confit.serialization.ValueSerializationTest.java

public static <T> T[] convert(final Object array, Class<T> wrapperClass) {
    final int arrayLength = Array.getLength(array);
    final T[] result = (T[]) Array.newInstance(wrapperClass, arrayLength);
    for (int i = 0; i < arrayLength; i++) {
        Array.set(result, i, Array.get(array, i));
    }//from  w  ww .  ja va2s  . co  m
    return result;
}

From source file:org.droidparts.reflect.util.TypeHelper.java

public static Object toTypeArr(Class<?> arrValType, String[] arr) {
    if (isByte(arrValType)) {
        ArrayList<Byte> list = toTypeColl(Byte.class, arr);
        Byte[] tArr = list.toArray(new Byte[list.size()]);
        return (arrValType == byte.class) ? toPrimitive(tArr) : tArr;
    } else if (isShort(arrValType)) {
        ArrayList<Short> list = toTypeColl(Short.class, arr);
        Short[] tArr = list.toArray(new Short[list.size()]);
        return (arrValType == short.class) ? toPrimitive(tArr) : tArr;
    } else if (isInteger(arrValType)) {
        ArrayList<Integer> list = toTypeColl(Integer.class, arr);
        Integer[] tArr = list.toArray(new Integer[list.size()]);
        return (arrValType == int.class) ? toPrimitive(tArr) : tArr;
    } else if (isLong(arrValType)) {
        ArrayList<Long> list = toTypeColl(Long.class, arr);
        Long[] tArr = list.toArray(new Long[list.size()]);
        return (arrValType == long.class) ? toPrimitive(tArr) : tArr;
    } else if (isFloat(arrValType)) {
        ArrayList<Float> list = toTypeColl(Float.class, arr);
        Float[] tArr = list.toArray(new Float[list.size()]);
        return (arrValType == float.class) ? toPrimitive(tArr) : tArr;
    } else if (isDouble(arrValType)) {
        ArrayList<Double> list = toTypeColl(Double.class, arr);
        Double[] tArr = list.toArray(new Double[list.size()]);
        return (arrValType == double.class) ? toPrimitive(tArr) : tArr;
    } else if (isBoolean(arrValType)) {
        ArrayList<Boolean> list = toTypeColl(Boolean.class, arr);
        Boolean[] tArr = list.toArray(new Boolean[list.size()]);
        return (arrValType == boolean.class) ? toPrimitive(tArr) : tArr;
    } else if (isCharacter(arrValType)) {
        ArrayList<Character> list = toTypeColl(Character.class, arr);
        Character[] tArr = list.toArray(new Character[list.size()]);
        return (arrValType == char.class) ? toPrimitive(tArr) : tArr;
    } else if (isString(arrValType)) {
        return arr;
    } else if (isEnum(arrValType)) {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        ArrayList<? extends Enum> list = (ArrayList<? extends Enum>) toTypeColl(arrValType, arr);
        Object enumArr = Array.newInstance(arrValType, list.size());
        for (int i = 0; i < list.size(); i++) {
            Array.set(enumArr, i, list.get(i));
        }/*from w w  w .  j a  v  a  2  s.  co m*/
        return enumArr;
    } else if (isUUID(arrValType)) {
        ArrayList<UUID> list = toTypeColl(UUID.class, arr);
        return list.toArray(new UUID[list.size()]);
    } else if (isDate(arrValType)) {
        ArrayList<Date> list = toTypeColl(Date.class, arr);
        return list.toArray(new Date[list.size()]);
    } else if (isJsonObject(arrValType)) {
        ArrayList<JSONObject> list = toTypeColl(JSONObject.class, arr);
        return list.toArray(new JSONObject[list.size()]);
    } else if (isJsonArray(arrValType)) {
        ArrayList<JSONArray> list = toTypeColl(JSONArray.class, arr);
        return list.toArray(new JSONArray[list.size()]);
    } else {
        throw new IllegalArgumentException("Unable to convert to" + arrValType);
    }
}

From source file:us.mn.state.health.lims.testanalyte.form.TestAnalyteTestResultActionForm.java

/**
 * <p>/*  w ww.  j a v  a2s  . c o  m*/
 * 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
 * 
 * @exception ConversionException
 *                if the specified value cannot be converted to the type
 *                required for this property
 * @exception IllegalArgumentException
 *                if there is no property of the specified name
 * @exception IllegalArgumentException
 *                if the specified property exists, but is not indexed
 * @exception IndexOutOfBoundsException
 *                if the specified index is outside the range of the
 *                underlying property
 */
public void set(String name, int index, Object value) {
    //System.out
    //.println("I am in set(String name, int index, Object value) with "
    //+ name + " " + index + " " + 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 {
            setAList(name, index, value);
        } catch (ClassCastException e) {
            //bugzilla 2154
            LogEvent.logError("TestAnalyteTestResultActionForm", "set()", e.getMessage());
            throw new ConversionException(e.getMessage());
        }
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }

}