Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:com.scit.sling.test.MockValueMap.java

@SuppressWarnings("unchecked")
private <T> T convertType(Object o, Class<T> type) {
    if (o == null) {
        return null;
    }/*from w ww.jav  a 2 s  . c  o  m*/
    if (o.getClass().isArray() && type.isArray()) {
        if (type.getComponentType().isAssignableFrom(o.getClass().getComponentType())) {
            return (T) o;
        } else {
            // we need to convert the elements in the array
            Object array = Array.newInstance(type.getComponentType(), Array.getLength(o));
            for (int i = 0; i < Array.getLength(o); i++) {
                Array.set(array, i, convertType(Array.get(o, i), type.getComponentType()));
            }
            return (T) array;
        }
    }
    if (o.getClass().isAssignableFrom(type)) {
        return (T) o;
    }
    if (String.class.isAssignableFrom(type)) {
        // Format dates
        if (o instanceof Calendar) {
            return (T) formatDate((Calendar) o);
        } else if (o instanceof Date) {
            return (T) formatDate((Date) o);
        } else if (o instanceof DateTime) {
            return (T) formatDate((DateTime) o);
        }
        return (T) String.valueOf(o);
    } else if (o instanceof DateTime) {
        DateTime dt = (DateTime) o;
        if (Calendar.class.isAssignableFrom(type)) {
            return (T) dt.toCalendar(Locale.getDefault());
        } else if (Date.class.isAssignableFrom(type)) {
            return (T) dt.toDate();
        } else if (Number.class.isAssignableFrom(type)) {
            return convertType(dt.getMillis(), type);
        }
    } else if (o instanceof Number && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) (Byte) ((Number) o).byteValue();
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) (Double) ((Number) o).doubleValue();
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) (Float) ((Number) o).floatValue();
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) (Integer) ((Number) o).intValue();
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) (Long) ((Number) o).longValue();
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) (Short) ((Number) o).shortValue();
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal(o.toString());
        }
    } else if (o instanceof Number && type.isPrimitive()) {
        final Number num = (Number) o;
        if (type == byte.class) {
            return (T) new Byte(num.byteValue());
        } else if (type == double.class) {
            return (T) new Double(num.doubleValue());
        } else if (type == float.class) {
            return (T) new Float(num.floatValue());
        } else if (type == int.class) {
            return (T) new Integer(num.intValue());
        } else if (type == long.class) {
            return (T) new Long(num.longValue());
        } else if (type == short.class) {
            return (T) new Short(num.shortValue());
        }
    } else if (o instanceof String && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) new Byte((String) o);
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) new Double((String) o);
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) new Float((String) o);
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) new Integer((String) o);
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) new Long((String) o);
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) new Short((String) o);
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal((String) o);
        }
    }
    throw new NotImplementedException(
            "Can't handle conversion from " + o.getClass().getName() + " to " + type.getName());
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Convert.//from   w w w  .  ja va2  s .c o m
 *
 * @param value the value
 * @param type the type
 * @return the object
 */
protected static Object convert(String value, Class<?> type) {
    Object newValue = null;
    if (type.isArray()) { // Indexed value into array
        newValue = ConvertUtils.convert(value, type.getComponentType());
    } else { // Value into scalar
        newValue = ConvertUtils.convert(value, type);
    }
    return newValue;
}

From source file:org.apache.axis.encoding.ser.BeanPropertyTarget.java

/**
 * set the bean property with specified value
 * @param value is the value./*ww  w.j a  va2  s .  c  o  m*/
 */
public void set(Object value) throws SAXException {

    try {
        // Set the value on the bean property. 
        // Use the indexed property method if the 
        // index is set.
        if (index < 0) {
            pd.set(object, value);
        } else {
            pd.set(object, index, value);
        }
    } catch (Exception e) {

        try {
            // If an exception occurred, 
            // see it the value can be converted into
            // the expected type.
            Class type = pd.getType();

            if (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive()
                    && type.isArray() && type.getComponentType().equals(Object.class)) {
                //we make our own array type here.
                type = Array.newInstance(JavaUtils.getWrapperClass(value.getClass().getComponentType()), 0)
                        .getClass();
            }

            if (JavaUtils.isConvertable(value, type)) {
                value = JavaUtils.convert(value, type);
                if (index < 0)
                    pd.set(object, value);
                else
                    pd.set(object, index, value);
            } else {
                // It is possible that an indexed
                // format was expected, but the
                // entire array was sent.  In such 
                // cases traverse the array and 
                // call the setter for each item.
                if (index == 0 && value.getClass().isArray() && !type.getClass().isArray()) {
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object item = JavaUtils.convert(Array.get(value, i), type);
                        pd.set(object, i, item);
                    }
                } else {
                    // Can't proceed.  Throw an exception that
                    // will be caught in the catch block below.
                    throw e;
                }
            }
        } catch (Exception ex) {
            // Throw a SAX exception with an informative
            // message.
            String field = pd.getName();
            if (index >= 0) {
                field += "[" + index + "]";
            }
            if (log.isErrorEnabled()) {
                //TODO: why is this just logged on the server-side and not thrown back to the client???
                String valueType = "null";
                if (value != null)
                    valueType = value.getClass().getName();
                log.error(Messages.getMessage("cantConvert02", new String[] { valueType, field,
                        (index >= 0) ? pd.getType().getComponentType().getName() : pd.getType().getName() }));
            }
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t != null) {
                    String classname = this.object.getClass().getName();
                    //show the context where this exception occured.
                    throw new SAXException(Messages.getMessage("cantConvert04", new String[] { classname, field,
                            (value == null) ? null : value.toString(), t.getMessage() }));
                }
            }
            throw new SAXException(ex);
        }
    }
}

From source file:org.controlhaus.webservice.generator.ExtensionMaker.java

private String getClassName(Class cls) {
    if (cls.isArray()) {
        return getClassName(cls.getComponentType()) + "[]";
    } else {//from  w w w.j  a v a2 s .c om
        return cls.getName().replace('$', '.');
    }
}

From source file:io.servicecomb.swagger.invocation.converter.ConverterMgr.java

protected Converter findArrayToCollection(Type src, Type target) {
    if (src.getClass().equals(Class.class) && ParameterizedType.class.isAssignableFrom(target.getClass())) {
        Class<?> srcCls = (Class<?>) src;
        ParameterizedType targetType = (ParameterizedType) target;
        Class<?> targetCls = (Class<?>) targetType.getRawType();

        if (srcCls.isArray() && srcCls.getComponentType().equals(targetType.getActualTypeArguments()[0])) {
            if (List.class.isAssignableFrom(targetCls)) {
                return arrayToList;
            }//from   ww  w.j a  v a 2 s  . co  m
            if (Set.class.isAssignableFrom(targetCls)) {
                return arrayToSet;
            }
        }
    }

    return null;
}

From source file:es.caib.zkib.jxpath.ri.model.dynabeans.DynaBeanPropertyPointer.java

/**
 * Convert a value to the appropriate property type.
 * @param value to convert//from w  ww .  j av a2 s  .c  o  m
 * @param element whether this should be a collection element.
 * @return conversion result
 */
private Object convert(Object value, boolean element) {
    DynaClass dynaClass = (DynaClass) dynaBean.getDynaClass();
    DynaProperty property = dynaClass.getDynaProperty(getPropertyName());
    Class type = property.getType();
    if (element) {
        if (type.isArray()) {
            type = type.getComponentType();
        } else {
            return value; // No need to convert
        }
    }

    try {
        return TypeUtils.convert(value, type);
    } catch (Exception ex) {
        String string = value == null ? "null" : value.getClass().getName();
        throw new JXPathTypeConversionException("Cannot convert value of class " + string + " to type " + type,
                ex);
    }
}

From source file:com.twosigma.beaker.kdb.KdbShell.java

/**
 * Try and convert an object to a List.//from  w w  w.  j a va  2s .  co m
 */
private List<?> toList(Object o) {
    Class<?> c = o.getClass();
    if (!c.isArray()) {
        return null;
    }

    if (c.getComponentType().isPrimitive()) {
        if (o instanceof boolean[]) {
            return Arrays.asList(ArrayUtils.toObject((boolean[]) o));
        } else if (o instanceof byte[]) {
            return Arrays.asList(ArrayUtils.toObject((byte[]) o));
        } else if (o instanceof short[]) {
            return Arrays.asList(ArrayUtils.toObject((short[]) o));
        } else if (o instanceof int[]) {
            return Arrays.asList(ArrayUtils.toObject((int[]) o));
        } else if (o instanceof long[]) {
            return Arrays.asList(ArrayUtils.toObject((long[]) o));
        } else if (o instanceof float[]) {
            return Arrays.asList(ArrayUtils.toObject((float[]) o));
        } else if (o instanceof double[]) {
            return Arrays.asList(ArrayUtils.toObject((double[]) o));
        } else if (o instanceof char[]) {
            return Arrays.asList(ArrayUtils.toObject((char[]) o));
        } else {
            throw new RuntimeException("Unhandled primitive type");
        }
    } else {
        return Arrays.asList((Object[]) o);
    }
}

From source file:ch.algotrader.esper.aggregation.GenericTALibFunction.java

@Override
public Class<?> getValueType() {

    // if we only have one outPutParam return that value
    // otherwise return the dynamically generated class
    if (this.outputParams.size() == 1) {
        Class<?> clazz = this.outputParams.values().iterator().next().getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType();
        } else {/*w  w  w. jav  a  2 s .  co m*/
            return clazz;
        }
    } else {
        return this.outputClass;
    }
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object genTypeValue(Type type) {
    Object ret = typeValueCache.get(type);
    if (ret != null) {
        return ret;
    }//  w w  w.ja v  a 2s .  c  om
    // only use positive primitive values
    if (type.equals(boolean.class)) {
        return rand.nextBoolean();
    } else if (type.equals(byte.class)) {
        return bytes[rand.nextInt(4)];
    } else if (type.equals(int.class)) {
        return rand.nextInt(1000000);
    } else if (type.equals(long.class)) {
        return Long.valueOf(rand.nextInt(1000000));
    } else if (type.equals(float.class)) {
        return rand.nextFloat();
    } else if (type.equals(double.class)) {
        return rand.nextDouble();
    } else if (type.equals(String.class)) {
        return String.format("%c%c%c", 'a' + rand.nextInt(26), 'a' + rand.nextInt(26), 'a' + rand.nextInt(26));
    } else if (type instanceof Class) {
        Class clazz = (Class) type;
        if (clazz.isArray()) {
            Class compClass = clazz.getComponentType();
            if (compClass != null) {
                ret = Array.newInstance(compClass, 2);
                Array.set(ret, 0, genTypeValue(compClass));
                Array.set(ret, 1, genTypeValue(compClass));
            }
        } else if (clazz.isEnum()) {
            Object[] values = clazz.getEnumConstants();
            ret = values[rand.nextInt(values.length)];
        } else if (clazz.equals(ByteBuffer.class)) {
            // return new ByteBuffer every time
            // to prevent potential side effects
            ByteBuffer buff = ByteBuffer.allocate(4);
            rand.nextBytes(buff.array());
            return buff;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type rawType = pt.getRawType();
        Type[] params = pt.getActualTypeArguments();
        // only support EnumSet<T>, List<T>, Set<T>, Map<K,V>
        if (rawType.equals(EnumSet.class)) {
            if (params[0] instanceof Class) {
                Class c = (Class) (params[0]);
                return EnumSet.allOf(c);
            }
        }
        if (rawType.equals(List.class)) {
            ret = Lists.newArrayList(genTypeValue(params[0]));
        } else if (rawType.equals(Set.class)) {
            ret = Sets.newHashSet(genTypeValue(params[0]));
        } else if (rawType.equals(Map.class)) {
            Map<Object, Object> map = Maps.newHashMap();
            map.put(genTypeValue(params[0]), genTypeValue(params[1]));
            ret = map;
        }
    }
    if (ret == null) {
        throw new IllegalArgumentException("type " + type + " is not supported");
    }
    typeValueCache.put(type, ret);
    return ret;
}

From source file:org.apache.tapestry.util.AdaptorRegistry.java

/**
 *  Returns the superclass of the given class, with a single tweak:  If the 
 *  search class is an array class, and the component type is an object class
 *  (but not Object), then the simple Object array class is returned.  This reflects
 *  the fact that an array of any class may be assignable to <code>Object[]</code>,
 *  even though the superclass of an array is always simply <code>Object</code>.
 * //  w  w  w  .j  a v a  2  s .  com
 **/

private Class getSuperclass(Class searchClass) {
    if (searchClass.isArray()) {
        Class componentType = searchClass.getComponentType();

        if (!componentType.isPrimitive() && componentType != Object.class)
            return Object[].class;
    }

    return searchClass.getSuperclass();
}