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:org.boris.xlloop.util.XLoperObjectConverter.java

/**
 * Creates a java object from an XLObject.
 * /*  ww  w . j  a  v a  2s.c  o m*/
 * @param obj.
 * @param hint.
 * 
 * @return Object.
 */
public Object createFrom(XLoper obj, Class hint, SessionContext sessionContext) {
    // If Excel passes a single value and the Java code expects an array,
    // try to convert based on the component type, and then create the
    // array.
    if (obj.type != XLoper.xlTypeMulti && hint.isArray()) {
        Object value = doTypeSwitch(obj, hint.getComponentType(), sessionContext);
        Object array = Array.newInstance(hint.getComponentType(), 1);
        Array.set(array, 0, value);
        return array;
    } else {
        return doTypeSwitch(obj, hint, sessionContext);
    }
}

From source file:org.moeaframework.core.PRNGTest.java

/**
 * Tests if the {@code shuffle} method produces valid permutations of a
 * typed array, and that the distribution of the values for each index are
 * approximately uniform./* www.j ava 2  s  .  c  om*/
 * 
 * @param type the class of the array
 * @param size the size of the array
 */
public void testShuffleArray(Class<?> type, int size) throws Exception {
    Object array = Array.newInstance(type.getComponentType(), size);
    DescriptiveStatistics[] statistics = new DescriptiveStatistics[size];

    for (int i = 0; i < size; i++) {
        // casts are needed when truncating the int
        if (type.getComponentType() == short.class) {
            Array.set(array, i, (short) i);
        } else if (type.getComponentType() == byte.class) {
            Array.set(array, i, (byte) i);
        } else {
            Array.set(array, i, i);
        }

        statistics[i] = new DescriptiveStatistics();
    }

    for (int i = 0; i < 50000; i++) {
        Method method = PRNG.class.getMethod("shuffle", type);
        method.invoke(null, array);

        Integer[] integerArray = new Integer[size];

        for (int j = 0; j < size; j++) {
            int value = ((Number) Array.get(array, j)).intValue();
            integerArray[j] = value;
            statistics[j].addValue(value);
        }

        testPermutation(size, integerArray);
    }

    for (int i = 0; i < size; i++) {
        testUniformDistribution(0, size - 1, statistics[i]);
    }
}

From source file:com.gigaspaces.persistency.metadata.DefaultSpaceDocumentMapper.java

private Object toArray(Class<?> type, BasicDBList value) {

    int length = value.size() - 1;
    Object array = Array.newInstance(type.getComponentType(), length);

    for (int i = 1; i < length + 1; i++) {
        Object v = fromDBObject(value.get(i));

        if (SpaceDocument.class.isAssignableFrom(type.getComponentType()))
            v = MongoDocumentObjectConverter.instance().toDocumentIfNeeded(v, SpaceDocumentSupport.CONVERT);

        if (type(type.getComponentType()) == TYPE_SHORT)
            v = ((Integer) v).shortValue();

        Array.set(array, i - 1, v);
    }//from w ww . j  a v a  2  s  . com

    return array;
}

From source file:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java

public Object fetchObjectField(int fieldNumber) {
    ClassLoaderResolver clr = ec.getClassLoaderResolver();
    AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);

    if (mmd.getType() == UUID.class) {
        String familyName = HBaseUtils.getFamilyName(cmd, fieldNumber);
        String columnName = HBaseUtils.getQualifierName(cmd, fieldNumber);
        byte[] bytes = result.getValue(familyName.getBytes(), columnName.getBytes());
        return fetchUUIDInternal(mmd, bytes);
    }/*from www  . j a va  2 s .  c  om*/

    int relationType = mmd.getRelationType(clr);
    if (mmd.isEmbedded() && Relation.isRelationSingleValued(relationType)) {
        // Persistable object embedded into table of this object
        Class embcls = mmd.getType();
        AbstractClassMetaData embcmd = ec.getMetaDataManager().getMetaDataForClass(embcls, clr);
        if (embcmd != null) {
            String tableName = HBaseUtils.getTableName(cmd);

            // Check for null value (currently need all columns to return null)
            // TODO Cater for null (use embmd.getNullIndicatorColumn/Value)
            EmbeddedMetaData embmd = mmd.getEmbeddedMetaData();
            AbstractMemberMetaData[] embmmds = embmd.getMemberMetaData();
            boolean isNull = true;
            for (int i = 0; i < embmmds.length; i++) {
                String familyName = HBaseUtils.getFamilyName(mmd, i, tableName);
                String columnName = HBaseUtils.getQualifierName(mmd, i);
                if (result.getValue(familyName.getBytes(), columnName.getBytes()) != null) {
                    isNull = false;
                    break;
                }
            }
            if (isNull) {
                return null;
            }

            ObjectProvider embSM = ec.newObjectProviderForEmbedded(mmd, embcmd, sm, fieldNumber);
            FieldManager ffm = new FetchEmbeddedFieldManager(embSM, result, mmd, tableName);
            embSM.replaceFields(embcmd.getAllMemberPositions(), ffm);
            return embSM.getObject();
        }
        throw new NucleusUserException(
                "Field " + mmd.getFullFieldName() + " marked as embedded but no such metadata");
    }

    String familyName = HBaseUtils.getFamilyName(cmd, fieldNumber);
    String columnName = HBaseUtils.getQualifierName(cmd, fieldNumber);
    Object value = readObjectField(familyName, columnName, result, fieldNumber, mmd);
    if (value == null) {
        return null;
    }

    if (Relation.isRelationSingleValued(relationType)) {
        if (mmd.isSerialized()) {
            return value;
        } else {
            // The stored value was the identity
            return ec.findObject(value, true, true, null);
        }
    } else if (Relation.isRelationMultiValued(relationType)) {
        if (mmd.hasCollection()) {
            if (mmd.isSerialized()) {
                return value;
            }

            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);
            }

            Collection collIds = (Collection) value;
            Iterator idIter = collIds.iterator();
            while (idIter.hasNext()) {
                Object elementId = idIter.next();
                coll.add(ec.findObject(elementId, true, true, null));
            }
            if (sm != null) {
                return sm.wrapSCOField(fieldNumber, coll, false, false, true);
            }
            return coll;
        } else if (mmd.hasMap()) {
            if (mmd.isSerialized()) {
                return value;
            }

            Map map;
            try {
                Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false);
                map = (Map) instanceType.newInstance();
            } catch (Exception e) {
                throw new NucleusDataStoreException(e.getMessage(), e);
            }

            Map mapIds = (Map) value;
            Iterator<Map.Entry> mapIdIter = mapIds.entrySet().iterator();
            while (mapIdIter.hasNext()) {
                Map.Entry entry = mapIdIter.next();
                Object mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                if (mmd.getMap().getKeyClassMetaData(clr, ec.getMetaDataManager()) != null) {
                    // Map key must be an "id"
                    mapKey = ec.findObject(mapKey, true, true, null);
                }
                if (mmd.getMap().getValueClassMetaData(clr, ec.getMetaDataManager()) != null) {
                    // Map value must be an "id"
                    mapValue = ec.findObject(mapValue, true, true, null);
                }
                map.put(mapKey, mapValue);
            }
            if (sm != null) {
                return sm.wrapSCOField(fieldNumber, map, false, false, true);
            }
            return map;
        } else if (mmd.hasArray()) {
            if (mmd.isSerialized()) {
                return value;
            }

            Collection arrIds = (Collection) value;
            Object array = Array.newInstance(mmd.getType().getComponentType(), arrIds.size());
            Iterator idIter = arrIds.iterator();
            int i = 0;
            while (idIter.hasNext()) {
                Object elementId = idIter.next();
                Array.set(array, i, ec.findObject(elementId, true, true, null));
            }
            return array;
        }
        throw new NucleusUserException("No container that isnt collection/map/array");
    } else {
        Object returnValue = value;
        if (!mmd.isSerialized()) {
            if (Enum.class.isAssignableFrom(mmd.getType())) {
                // Persisted as a String, so convert back
                // TODO Retrieve as number when requested
                return Enum.valueOf(mmd.getType(), (String) value);
            }

            ObjectStringConverter strConv = ec.getNucleusContext().getTypeManager()
                    .getStringConverter(mmd.getType());
            if (strConv != null) {
                // Persisted as a String, so convert back
                String strValue = (String) value;
                returnValue = strConv.toObject(strValue);
            }
        }
        if (sm != null) {
            return sm.wrapSCOField(fieldNumber, returnValue, false, false, true);
        }
        return returnValue;
    }
}

From source file:com.espertech.esper.epl.core.SelectExprInsertEventBean.java

private void initializeCtorInjection(ExprEvaluator[] exprEvaluators, StreamTypeService typeService,
        Object[] expressionReturnTypes, MethodResolutionService methodResolutionService,
        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;
        }/*w  ww . ja  v  a 2s.  com*/

        if (columnType instanceof EventType) {
            EventType columnEventType = (EventType) columnType;
            final Class returnType = columnEventType.getUnderlyingType();
            int streamNum = 0;
            for (int j = 0; j < typeService.getEventTypes().length; j++) {
                if (typeService.getEventTypes()[j] == columnEventType) {
                    streamNum = j;
                    break;
                }
            }
            final int streamNumEval = streamNum;
            evaluators[i] = new ExprEvaluator() {
                public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                        ExprEvaluatorContext exprEvaluatorContext) {
                    EventBean event = eventsPerStream[streamNumEval];
                    if (event != null) {
                        return event.getUnderlying();
                    }
                    return null;
                }

                public Class getType() {
                    return returnType;
                }

                public Map<String, Object> getEventType() {
                    return null;
                }
            };
            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;
                }

                public Map<String, Object> getEventType() {
                    return null;
                }
            };
            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 = methodResolutionService.resolveCtor(beanEventType.getUnderlyingType(), ctorTypes);
        FastClass fastClass = FastClass.create(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);
    }

    this.exprEvaluators = evaluators;
    this.wideners = new TypeWidener[evaluators.length];
    this.eventManufacturer = new EventBeanManufacturerCtor(fctor, beanEventType, eventAdapterService);
}

From source file:org.paxle.tools.ieporter.cm.impl.ConfigurationIEPorter.java

@SuppressWarnings("unchecked")
public Dictionary<String, Object> importConfiguration(Document doc) {
    if (doc == null)
        return null;

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    try {//from  ww  w  . j  av  a 2s.com
        Element configElement = doc.getDocumentElement();

        // getting the service-pid
        Element pidElement = (Element) configElement.getElementsByTagName(Constants.SERVICE_PID).item(0);
        props.put(Constants.SERVICE_PID, pidElement.getFirstChild().getNodeValue());

        // loop through all properties
        Element propsElement = (Element) configElement.getElementsByTagName(ELEM_PROPERTIES).item(0);
        NodeList propsList = propsElement.getElementsByTagName(ELEM_PROPERTY);

        for (int i = 0; i < propsList.getLength(); i++) {
            Element propertyElement = (Element) propsList.item(i);

            Object value = null;
            String key = propertyElement.getAttributes().getNamedItem(ATTRIBUTE_PROPERTY_KEY).getNodeValue();
            String type = propertyElement.getAttributes().getNamedItem(ATTRIB_PROPERTY_TYPE).getNodeValue();

            if (type.endsWith("[]") || type.equals(Vector.class.getSimpleName())) {
                Element valueElements = (Element) propertyElement.getElementsByTagName(ELEM_VALUES).item(0);
                NodeList valueElementList = valueElements.getElementsByTagName(ELEM_VALUE);

                if (type.endsWith("[]")) {
                    // get type class
                    Class clazz = NAMELOOKUP.get(type.substring(0, type.length() - 2));

                    // create a new array
                    value = Array.newInstance(clazz, valueElementList.getLength());
                } else {
                    // create a new vector
                    value = new Vector();
                }

                // append all values to the array/vector
                for (int j = 0; j < valueElementList.getLength(); j++) {
                    Element valueElement = (Element) valueElementList.item(j);
                    Object valueObj = this.valueOf(type, valueElement);

                    if (type.endsWith("[]")) {
                        Array.set(value, j, valueObj);
                    } else {
                        ((Vector<Object>) value).add(valueObj);
                    }
                }
            } else {
                Element valueElement = (Element) propertyElement.getElementsByTagName(ELEM_VALUE).item(0);

                // get concrete value
                value = this.valueOf(type, valueElement);
            }

            // add value
            props.put(key, value);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return props;
}

From source file:org.jaffa.util.BeanHelper.java

/** Clones the input bean, performing a deep copy of its properties.
 * @param bean the bean to be cloned.//  w  w w. jav a 2  s. c  o  m
 * @param deepCloneForeignField if false, then the foreign-fields of a GraphDataObject will not be deep cloned.
 * @return a clone of the input bean.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 * @throws InstantiationException if the bean cannot be instantiated.
 * @throws IntrospectionException if an exception occurs during introspection.
 */
public static Object cloneBean(Object bean, boolean deepCloneForeignField) throws IllegalAccessException,
        InvocationTargetException, InstantiationException, IntrospectionException {
    if (bean == null)
        return bean;

    Class beanClass = bean.getClass();

    // Return the input as-is, if immutable
    if (beanClass == String.class || beanClass == Boolean.class || Number.class.isAssignableFrom(beanClass)
            || IDateBase.class.isAssignableFrom(beanClass) || Currency.class.isAssignableFrom(beanClass)
            || beanClass.isPrimitive()) {
        return bean;
    }

    // Handle an array
    if (beanClass.isArray()) {
        Class componentType = beanClass.getComponentType();
        int length = Array.getLength(bean);
        Object clone = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Object arrayElementClone = cloneBean(Array.get(bean, i), deepCloneForeignField);
            Array.set(clone, i, arrayElementClone);
        }
        return clone;
    }

    // Handle a Collection
    if (bean instanceof Collection) {
        Collection clone = (Collection) bean.getClass().newInstance();
        for (Object collectionElement : (Collection) bean) {
            Object collectionElementClone = cloneBean(collectionElement, deepCloneForeignField);
            clone.add(collectionElementClone);
        }
        return clone;
    }

    // Handle a Map
    if (bean instanceof Map) {
        Map clone = (Map) bean.getClass().newInstance();
        for (Iterator i = ((Map) bean).entrySet().iterator(); i.hasNext();) {
            Map.Entry me = (Map.Entry) i.next();
            Object keyClone = cloneBean(me.getKey(), deepCloneForeignField);
            Object valueClone = cloneBean(me.getValue(), deepCloneForeignField);
            clone.put(keyClone, valueClone);
        }
        return clone;
    }

    // Invoke the 'public Object clone()' method, if available
    if (bean instanceof Cloneable) {
        try {
            Method cloneMethod = beanClass.getMethod("clone");
            return cloneMethod.invoke(bean);
        } catch (NoSuchMethodException e) {
            // do nothing
        }
    }

    // Create a clone using bean introspection
    Object clone = beanClass.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            // Obtain a GraphMapping; only if foreign-fields are not to be cloned
            //Use reflection to achieve the following:
            //GraphMapping graphMapping = !deepCloneForeignField && bean instanceof GraphDataObject ? MappingFactory.getInstance(bean) : null;
            Object graphMapping = null;
            Method isForeignFieldMethod = null;
            try {
                if (!deepCloneForeignField
                        && Class.forName("org.jaffa.soa.graph.GraphDataObject").isInstance(bean)) {
                    graphMapping = Class.forName("org.jaffa.soa.dataaccess.MappingFactory")
                            .getMethod("getInstance", Object.class).invoke(null, bean);
                    isForeignFieldMethod = graphMapping.getClass().getMethod("isForeignField", String.class);
                }
            } catch (Exception e) {
                // do nothing since JaffaSOA may not be deployed
                if (log.isDebugEnabled())
                    log.debug("Exception in obtaining the GraphMapping", e);
            }

            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    // Do not clone a foreign-field
                    Object property = pd.getReadMethod().invoke(bean);

                    //Use reflection to achieve the following:
                    //Object propertyClone = graphMapping != null && graphMapping.isForeignField(pd.getName()) ? property : cloneBean(property, deepCloneForeignField);
                    Object propertyClone = null;
                    boolean propertyCloned = false;
                    if (graphMapping != null && isForeignFieldMethod != null) {
                        try {
                            if ((Boolean) isForeignFieldMethod.invoke(graphMapping, pd.getName())) {
                                propertyClone = property;
                                propertyCloned = true;
                            }
                        } catch (Exception e) {
                            // do nothing since JaffaSOA may not be deployed
                            if (log.isDebugEnabled())
                                log.debug("Exception in invoking GraphMapping.isForeignField()", e);
                        }
                    }
                    if (!propertyCloned)
                        propertyClone = cloneBean(property, deepCloneForeignField);

                    pd.getWriteMethod().invoke(clone, propertyClone);
                }
            }
        }
    }
    return clone;
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

/** Read a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *///from w w w  .  ja va2s  .co  m
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, CObjectWritable objectWritable, CloudataConf conf,
        boolean arrayComponent, Class componentClass) throws IOException {
    String className;
    if (arrayComponent) {
        className = componentClass.getName();
    } else {
        className = CUTF8.readString(in);
        //SANGCHUL
        //   System.out.println("SANGCHUL] className:" + className);
    }

    Class<?> declaredClass = PRIMITIVE_NAMES.get(className);
    if (declaredClass == null) {
        try {
            declaredClass = conf.getClassByName(className);
        } catch (ClassNotFoundException e) {
            //SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class[className=" + className + "]", e);
        }
    }

    Object instance;

    if (declaredClass.isPrimitive()) { // primitive types

        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }

    } else if (declaredClass.isArray()) { // array
        //System.out.println("SANGCHUL] is array");
        int length = in.readInt();
        //System.out.println("SANGCHUL] array length : " + length);
        //System.out.println("Read:in.readInt():" + length);
        if (declaredClass.getComponentType() == Byte.TYPE) {
            byte[] bytes = new byte[length];
            in.readFully(bytes);
            instance = bytes;
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            instance = readColumnValue(in, conf, declaredClass, length);
        } else {
            Class componentType = declaredClass.getComponentType();

            // SANGCHUL
            //System.out.println("SANGCHUL] componentType : " + componentType.getName());

            instance = Array.newInstance(componentType, length);
            for (int i = 0; i < length; i++) {
                Object arrayComponentInstance = readObject(in, null, conf, !componentType.isArray(),
                        componentType);
                Array.set(instance, i, arrayComponentInstance);
                //Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass == String.class) { // String
        instance = CUTF8.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, CUTF8.readString(in));
    } else if (declaredClass == ColumnValue.class) {
        //ColumnValue?  ?? ?? ?  ? ?.
        //? ?   ? ? ? ? . 
        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            if (typeDiff == TYPE_DIFF) {
                instanceClass = conf.getClassByName(CUTF8.readString(in));
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("readObject can't find class", e);
        }
        ColumnValue columnValue = new ColumnValue();
        columnValue.readFields(in);
        instance = columnValue;
    } else { // Writable

        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            // SANGCHUL
            //System.out.println("SANGCHUL] typeDiff : " + typeDiff);
            //System.out.println("Read:in.readShort():" + typeDiff);
            if (typeDiff == TYPE_DIFF) {
                // SANGCHUL
                String classNameTemp = CUTF8.readString(in);
                //System.out.println("SANGCHUL] typeDiff : " + classNameTemp);
                instanceClass = conf.getClassByName(classNameTemp);
                //System.out.println("Read:UTF8.readString(in):" + instanceClass.getClass());
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {

            // SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class", e);
        }

        CWritable writable = CWritableFactories.newInstance(instanceClass, conf);
        writable.readFields(in);
        //System.out.println("Read:writable.readFields(in)");
        instance = writable;

        if (instanceClass == NullInstance.class) { // null
            declaredClass = ((NullInstance) instance).declaredClass;
            instance = null;
        }
    }

    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }

    return instance;
}

From source file:pe.com.mmh.sisgap.utils.BasicDynaBean.java

/**
 * Set the value of an indexed property with the specified name.
 *
 * @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//from w w  w .j  a  va 2  s. c  o  m
 * @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) {

    Object prop = values.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:org.apache.axis.utils.JavaUtils.java

/** Utility function to convert an Object to some desired Class.
 *
 * Right now this works for:// w  w w. ja  v  a  2  s . com
 *     arrays <-> Lists,
 *     Holders <-> held values
 * @param arg the array to convert
 * @param destClass the actual class we want
 */
public static Object convert(Object arg, Class destClass) {
    if (destClass == null) {
        return arg;
    }

    Class argHeldType = null;
    if (arg != null) {
        argHeldType = getHolderValueType(arg.getClass());
    }

    if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug(Messages.getMessage("convert00", clsName, destClass.getName()));
    }

    // See if a previously converted value is stored in the argument.
    Object destValue = null;
    if (arg instanceof ConvertCache) {
        destValue = ((ConvertCache) arg).getConvertedValue(destClass);
        if (destValue != null)
            return destValue;
    }

    // Get the destination held type or the argument held type if they exist
    Class destHeldType = getHolderValueType(destClass);

    // Convert between Axis special purpose HexBinary and byte[]
    if (arg instanceof HexBinary && destClass == byte[].class) {
        return ((HexBinary) arg).getBytes();
    } else if (arg instanceof byte[] && destClass == HexBinary.class) {
        return new HexBinary((byte[]) arg);
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }
    if (arg instanceof Date && destClass == Calendar.class) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) arg);
        return calendar;
    }

    // Convert between Calendar and java.sql.Date
    if (arg instanceof Calendar && destClass == java.sql.Date.class) {
        return new java.sql.Date(((Calendar) arg).getTime().getTime());
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    // Convert an AttachmentPart to the given destination class.
    if (isAttachmentSupported()
            && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) {
        try {
            String destName = destClass.getName();
            if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class
                    || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class
                    || destName.equals("javax.mail.internet.MimeMultipart")) {
                DataHandler handler = null;
                if (arg instanceof AttachmentPart) {
                    handler = ((AttachmentPart) arg).getDataHandler();
                } else if (arg instanceof DataHandler) {
                    handler = (DataHandler) arg;
                }
                if (destClass == Image.class) {
                    // Note:  An ImageIO component is required to process an Image
                    // attachment, but if the image would be null
                    // (is.available == 0) then ImageIO component isn't needed
                    // and we can return null.
                    InputStream is = handler.getInputStream();
                    if (is.available() == 0) {
                        return null;
                    } else {
                        ImageIO imageIO = ImageIOFactory.getImageIO();
                        if (imageIO != null) {
                            return getImageFromStream(is);
                        } else {
                            log.info(Messages.getMessage("needImageIO"));
                            return arg;
                        }
                    }
                } else if (destClass == javax.xml.transform.Source.class) {
                    // For a reason unknown to me, the handler's
                    // content is a String.  Convert it to a
                    // StreamSource.
                    return new StreamSource(handler.getInputStream());
                } else if (destClass == OctetStream.class || destClass == byte[].class) {
                    InputStream in = null;
                    if (arg instanceof InputStream) {
                        in = (InputStream) arg;
                    } else {
                        in = handler.getInputStream();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int byte1 = -1;
                    while ((byte1 = in.read()) != -1)
                        baos.write(byte1);
                    return new OctetStream(baos.toByteArray());
                } else if (destClass == DataHandler.class) {
                    return handler;
                } else {
                    return handler.getContent();
                }
            }
        } catch (IOException ioe) {
        } catch (SOAPException se) {
        }
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class)
            && destClass.getComponentType().isAssignableFrom(arg.getClass())) {
        Object array = Array.newInstance(destClass.getComponentType(), 1);
        Array.set(array, 0, arg);
        return array;
    }

    // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[])
    if (arg != null && destClass.isArray()) {
        Object newArg = ArrayUtil.convertObjectToArray(arg, destClass);
        if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) {
            return newArg;
        }
    }

    // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT)
    if (arg != null && arg.getClass().isArray()) {
        Object newArg = ArrayUtil.convertArrayToObject(arg, destClass);
        if (newArg != null)
            return newArg;
    }

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))
            && ((destHeldType == null && argHeldType == null)
                    || (destHeldType != null && argHeldType != null))) {
        return arg;
    }

    // Take care of Holder conversion
    if (destHeldType != null) {
        // Convert arg into Holder holding arg.
        Object newArg = convert(arg, destHeldType);
        Object argHolder = null;
        try {
            argHolder = destClass.newInstance();
            setHolderValue(argHolder, newArg);
            return argHolder;
        } catch (Exception e) {
            return arg;
        }
    } else if (argHeldType != null) {
        // Convert arg into the held type
        try {
            Object newArg = getHolderValue(arg);
            return convert(newArg, destClass);
        } catch (HolderException e) {
            return arg;
        }
    }

    // Flow to here indicates that neither arg or destClass is a Holder

    // Check to see if the argument has a prefered destination class.
    if (arg instanceof ConvertCache && ((ConvertCache) arg).getDestClass() != destClass) {
        Class hintClass = ((ConvertCache) arg).getDestClass();
        if (hintClass != null && hintClass.isArray() && destClass.isArray()
                && destClass.isAssignableFrom(hintClass)) {
            destClass = hintClass;
            destValue = ((ConvertCache) arg).getConvertedValue(destClass);
            if (destValue != null)
                return destValue;
        }
    }

    if (arg == null) {
        return arg;
    }

    // The arg may be an array or List 
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }
    if (destClass.isArray()) {
        if (destClass.getComponentType().isPrimitive()) {

            Object array = Array.newInstance(destClass.getComponentType(), length);
            // Assign array elements
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    Array.set(array, i, Array.get(arg, i));
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    Array.set(array, idx++, i.next());
                }
            }
            destValue = array;

        } else {
            Object[] array;
            try {
                array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
            } catch (Exception e) {
                return arg;
            }

            // Use convert to assign array elements.
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    array[idx++] = convert(i.next(), destClass.getComponentType());
                }
            }
            destValue = array;
        }
    } else if (Collection.class.isAssignableFrom(destClass)) {
        Collection newList = null;
        try {
            // if we are trying to create an interface, build something
            // that implements the interface
            if (destClass == Collection.class || destClass == List.class) {
                newList = new ArrayList();
            } else if (destClass == Set.class) {
                newList = new HashSet();
            } else {
                newList = (Collection) destClass.newInstance();
            }
        } catch (Exception e) {
            // Couldn't build one for some reason... so forget it.
            return arg;
        }

        if (arg.getClass().isArray()) {
            for (int j = 0; j < length; j++) {
                newList.add(Array.get(arg, j));
            }
        } else {
            for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                newList.add(j.next());
            }
        }
        destValue = newList;
    } else {
        destValue = arg;
    }

    // Store the converted value in the argument if possible.
    if (arg instanceof ConvertCache) {
        ((ConvertCache) arg).setConvertedValue(destClass, destValue);
    }
    return destValue;
}