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.sunchenbin.store.feilong.core.bean.ConvertUtil.java

/**
 * ? Primitive./*  w w w  .  ja  va 2  s.com*/
 *
 * @param o
 *            the o
 * @return true, if checks if is primitive array
 * 
 * @since 1.4.0
 */
private static boolean isPrimitiveArray(Object o) {
    // Allocate a new Array
    Class<? extends Object> klass = o.getClass();

    if (!klass.isArray()) {
        return false;
    }

    Class<?> componentType = klass.getComponentType();
    //
    return componentType.isPrimitive();
}

From source file:com.bstek.dorado.data.entity.EntityUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T toEntity(Object object, DataType dataType) throws Exception {
    if (isSimpleValue(object)) {
        return (T) object;
    }//from   w w w .j  a  va  2 s.com

    // Expression
    if (object instanceof Expression) {
        object = ((Expression) object).evaluate();
    }

    Class<?> cl = object.getClass();
    if (object instanceof Collection) {
        Collection<?> entities = (Collection<?>) object;
        if (entities instanceof EntityCollection<?>) {
            DataType currentDataType = getDataType(entities);
            if (currentDataType != dataType && dataType != null) {
                ((EntityCollection<?>) entities).setDataType((AggregationDataType) dataType);
            }
            return (T) object;
        }
    } else {
        EntityEnhancer entityEnhancer = getEntityEnhancer(object);
        if (entityEnhancer != null) {
            DataType currentDataType = entityEnhancer.getDataType();
            if (currentDataType != dataType && dataType != null) {
                entityEnhancer.setDataType((EntityDataType) dataType);
            }
            return (T) object;
        }
    }

    boolean useProxy = true;
    if (dataType == null) {
        dataType = getDataType(cl);
    }

    if (dataType != null) {
        Class<?> matchType = dataType.getMatchType();
        if (matchType != null) {
            boolean matching = false;
            if (matchType.isPrimitive()) {
                matching = ClassUtils.primitiveToWrapper(matchType).equals(cl);
            } else {
                matching = matchType.isAssignableFrom(cl);
            }
            if (!matching) {
                if (dataType instanceof EntityDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof EntityDataType) {
                        matching = true;
                        useProxy = false;
                    }
                } else if (dataType instanceof AggregationDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof AggregationDataType) {
                        matching = true;
                    }
                }

                if (!matching) {
                    throw new IllegalArgumentException(
                            "Result type mismatch. expect [" + matchType + "] but [" + cl + "].");
                }
            }
        }
    }

    if (object instanceof Collection) {
        // Collection???
        AggregationDataType AggregationDataType = (AggregationDataType) dataType;
        if (object instanceof List) {
            object = new EntityList((List) object, AggregationDataType);
        } else if (object instanceof Set) {
            object = new EntitySet((Set) object, AggregationDataType);
        } else {
            throw new IllegalArgumentException("Unsupported result type [" + cl.getName() + "].");
        }
    } else if (object.getClass().isArray()) {
        Class type = object.getClass();
        if (isSimpleType(type.getComponentType())) {
            return (T) object;
        } else {
            // ??java.util.List
            logger.warn("Dorado converted a " + object.getClass() + " to " + List.class + " automatically.");

            List list = CollectionUtils.arrayToList(object);
            object = new EntityList(list, (AggregationDataType) dataType);
        }
    } else {
        // TODO Entity????
        // Entity???
        EntityDataType entityDataType = (EntityDataType) dataType;
        if (!(entityDataType instanceof CustomEntityDataType)) {
            if (useProxy) {
                // ????
                if (object instanceof EnhanceableEntity) {
                    EnhanceableEntity enhanceableEntity = (EnhanceableEntity) object;
                    if (enhanceableEntity.getEntityEnhancer() == null) {
                        EntityEnhancer entityEnhancer;
                        if (object instanceof Map) {
                            entityEnhancer = new EnhanceableMapEntityEnhancer(entityDataType);
                        } else {
                            entityEnhancer = new EnhanceableBeanEntityEnhancer(entityDataType,
                                    object.getClass());
                        }
                        enhanceableEntity.setEntityEnhancer(entityEnhancer);
                    }
                    return (T) object;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            object.getClass(), object);
                    object = ProxyBeanUtils.proxyBean(object, mis);
                }
            } else {
                // ????
                Class<?> creationType = entityDataType.getCreationType();
                if (creationType == null) {
                    creationType = entityDataType.getMatchType();
                }

                Map map;
                if (object instanceof Map) {
                    map = (Map) object;
                } else {
                    map = BeanMap.create(object);
                }

                if (creationType == null) {
                    Record record = new Record(map);
                    record.setEntityEnhancer(new EnhanceableMapEntityEnhancer(entityDataType));
                    object = record;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            creationType, null);
                    object = ProxyBeanUtils.createBean(creationType, mis);
                    setValues(object, map);
                }
            }
        } else {
            object = ((CustomEntityDataType) entityDataType).toMap(object);
        }
    }
    return (T) object;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

private static void dumpObject(JSONArray jsonArray, Class type, Object array, int index)
        throws JSONSerializationException, JSONException {
    if (type.isPrimitive()) {
        jsonArray.put(String.valueOf(Array.get(array, index)));
    } else if (type == String.class) {
        String val = (String) Array.get(array, index);
        if (val != null) {
            jsonArray.put(val);
        }//ww  w  .ja v a2s  .  co  m
    } else if (JSONSerializable.class.isAssignableFrom(type)) {
        JSONSerializable o = (JSONSerializable) Array.get(array, index);
        JSONObject jobj = serializeJSONObject(o);
        jsonArray.put(jobj);
    } else if (type.isArray() && array != null) {
        Class compType = type.getComponentType();
        Object subArray = Array.get(array, index);
        int len = Array.getLength(subArray);
        JSONArray arr = new JSONArray();
        for (int k = 0; k < len; ++k) {
            dumpObject(arr, compType, subArray, k);
        }
        jsonArray.put(arr);
    }
}

From source file:edu.umich.flowfence.common.ParceledPayload.java

public static boolean canParcelType(Class<?> clazz, boolean allowVoid) {
    // All primitives and wrapper types are parcelable, except Character and Void.
    if (ClassUtils.isPrimitiveOrWrapper(clazz)) {
        return (clazz != char.class && clazz != Character.class
                && (allowVoid || (clazz != void.class && clazz != Void.class)));
    }/*from  w  w  w . jav a2 s . co  m*/
    // String and CharSequence are parcelable.
    if (clazz == String.class || ClassUtils.isAssignable(clazz, CharSequence.class)) {
        return true;
    }
    // Object arrays are parcelable if their component type is parcelable.
    // Primitive boolean[], byte[], int[], and long[] arrays are parcelable.
    if (clazz.isArray()) {
        Class<?> componentType = clazz.getComponentType();
        if (componentType.isPrimitive()) {
            return (componentType == int.class || componentType == long.class || componentType == byte.class
                    || componentType == boolean.class);
        } else {
            return canParcelType(componentType, false);
        }
    }
    // Parcelable, obviously, is parcelable.
    // This covers Bundle as well.
    if (ClassUtils.isAssignable(clazz, Parcelable.class)) {
        return true;
    }
    // Map, List, and SparseArray are all parcelable, with restrictions on their component type
    // that we can't check here.
    if (ClassUtils.isAssignable(clazz, Map.class) || ClassUtils.isAssignable(clazz, List.class)
            || ClassUtils.isAssignable(clazz, SparseArray.class)) {
        return true;
    }
    // IBinder is parcelable.
    if (ClassUtils.isAssignable(clazz, IBinder.class)) {
        return true;
    }
    // Serializable is parcelable.
    if (ClassUtils.isAssignable(clazz, Serializable.class)) {
        return true;
    }
    return false;
}

From source file:be.fedict.eid.applet.service.impl.tlv.TlvParser.java

private static <T> T parseThrowing(byte[] file, Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    Field[] fields = tlvClass.getDeclaredFields();
    Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    for (Field field : fields) {
        TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null == tlvFieldAnnotation) {
            continue;
        }/*w w w  .  j a va2 s.  c  om*/
        int tagId = tlvFieldAnnotation.value();
        if (tlvFields.containsKey(new Integer(tagId))) {
            throw new IllegalArgumentException("TLV field duplicate: " + tagId);
        }
        tlvFields.put(new Integer(tagId), field);
    }
    T tlvObject = tlvClass.newInstance();

    int idx = 0;
    while (idx < file.length - 1) {
        byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            Field tlvField = tlvFields.get(new Integer(tag));
            Class<?> tlvType = tlvField.getType();
            ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            LOG.debug("setting field: " + tlvField.getName());
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

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

private static Object readColumnValue(DataInput in, CloudataConf conf, Class<?> declaredClass, int length)
        throws IOException {
    long startTime = System.currentTimeMillis();

    int totalByteSize = in.readInt();
    byte[] buf = new byte[totalByteSize];
    in.readFully(buf);//from  w w  w .ja va2s  .c om
    long endTime = System.currentTimeMillis();
    //LOG.fatal("readColumnValue1:length=" + length + ",bytes=" + totalByteSize + ",time=" + (endTime - startTime));

    DataInputStream byteDataIn = new DataInputStream(new ByteArrayInputStream(buf));

    ColumnValue[] instance = (ColumnValue[]) Array.newInstance(declaredClass.getComponentType(), length);
    //startTime = System.currentTimeMillis();
    Class componentClass = declaredClass.getComponentType();
    for (int i = 0; i < length; i++) {
        //Array.set(instance, i, readObject(byteDataIn, null, conf, true, declaredClass.getComponentType()));
        instance[i] = (ColumnValue) readObject(byteDataIn, null, conf, true, componentClass);
    }
    byteDataIn.close();
    byteDataIn = null;
    buf = null;
    //endTime = System.currentTimeMillis();
    //LOG.fatal("readColumnValue2:time=" + (endTime - startTime));
    return instance;
}

From source file:org.istsms.util.Javabean2JSON.java

private static JSONArray _toJSONArray(Object value, Class c) {
    if (value == null)
        return null;
    if (!c.isArray())
        return null;
    if (value.getClass().isArray()) {
        //it's an array!                  
        Vector v = new Vector();
        int length = Array.getLength(value);
        for (int j = 0; j < length; j++) {
            Object element = Array.get(value, j);
            if (element != null) {
                if (element.getClass().isArray()) {
                    v.add(_toJSONArray(element, c.getComponentType()));
                } else {
                    String suggestedComponentType = c.getComponentType().getCanonicalName();
                    if (isCalendar(element.getClass().getCanonicalName())) {
                        v.add(fromJavaCalendar((java.util.Calendar) element));
                    } else if (isPrimitive(element.getClass().getCanonicalName())) {
                        v.add(equalPrimitive(element.getClass().getCanonicalName(), suggestedComponentType)
                                ? element.toString()
                                //                            (element instanceof java.util.Calendar)
                                //                               ?""+((java.util.Calendar)element).getTime().getTime()   
                                //                            :element.toString()

                                : toJSONObject(element));
                    } else {
                        v.add(suggestedComponentType.equals(element.getClass().getCanonicalName())
                                ? _toJSONObject(element)
                                : toJSONObject(element));
                    }/*from w w  w.  j  a  v a 2s.  c o m*/
                }
            } else {
                v.add(JSONObject.NULL);
            }
        }
        return new JSONArray(v);
    }
    return null;
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?/*from  w ww  . j a  va  2s .  c  om*/
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}

From source file:be.fedict.commons.eid.consumer.tlv.TlvParser.java

private static <T> T parseThrowing(final byte[] file, final Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    final Field[] fields = tlvClass.getDeclaredFields();
    final Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    final T tlvObject = tlvClass.newInstance();
    for (Field field : fields) {
        final TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null != tlvFieldAnnotation) {
            final int tagId = tlvFieldAnnotation.value();
            if (tlvFields.containsKey(new Integer(tagId))) {
                throw new IllegalArgumentException("TLV field duplicate: " + tagId);
            }//from   www  .j  av  a 2s  . c o  m
            tlvFields.put(new Integer(tagId), field);
        }
        final OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class);
        if (null != originalDataAnnotation) {
            field.setAccessible(true);
            field.set(tlvObject, file);
        }
    }

    int idx = 0;
    while (idx < file.length - 1) {
        final byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            final Field tlvField = tlvFields.get(new Integer(tag));
            final Class<?> tlvType = tlvField.getType();
            final ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            final byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                final Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                final DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleArrayType(Class<?> classz, StringBuilder sb, JsonSchemaProperty propertyDescriptor,
        Map<String, String> declarations, String uriPrefix) {
    boolean result = false;
    Map<String, Boolean> flags = new HashMap<String, Boolean>();
    flags.put("hasTitle", false);
    flags.put("hasDescription", false);
    flags.put("hasType", false);
    flags.put("hasEnum", false);

    Class<?> itemClass = null;
    String prepend = ", ";
    if (classz.isArray()) {
        sb.append("\"type\":\"array\"");
        itemClass = classz.getComponentType();
        flags.put("hasType", true);
        result = true;//from ww  w. j  a  v  a 2  s . c o m
    } else if (Collection.class.isAssignableFrom(classz)) {
        if (propertyDescriptor.collectionContains().equals(JsonSchemaProperty.DEFAULT.class))
            throw new IllegalArgumentException(String.format(
                    "The property descriptor is not valid.  You must specify collectionContains for collection type properties. %s",
                    propertyDescriptor));
        itemClass = propertyDescriptor.collectionContains();
        sb.append("\"type\":\"array\"");
        flags.put("hasType", false);
        result = true;
    }
    if (result == true) {

        handlePropertyDescriptor(sb, propertyDescriptor, flags, prepend, result, uriPrefix);

        boolean inline = true;
        StringBuilder sb2 = new StringBuilder();
        sb2.append("{");
        if (!handleSimpleType(itemClass, sb2, null, declarations, uriPrefix)) {
            if (!handleArrayType(itemClass, sb2, propertyDescriptor, declarations, uriPrefix)) {
                inline = false;
                handleObjectType(itemClass, sb2, propertyDescriptor, declarations, false, uriPrefix);
            }
        }
        sb2.append("}");

        if (inline) {
            sb.append(prepend);
            sb.append("\"items\":");
            sb.append(sb2.toString());
        } else {
            String id = null;
            JsonSchemaClass jsc = itemClass.getAnnotation(JsonSchemaClass.class);
            if (jsc != null)
                id = jsc.id();
            else
                id = itemClass.getName();
            declarations.put(id, sb2.toString());

            sb.append(prepend);
            sb.append("\"items\":{\"$ref\":\"" + uriPrefix);
            sb.append(id);
            sb.append("\"}");
        }
    }
    return result;
}