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.glaf.core.util.ReflectUtils.java

public static boolean isPrimitives(Class<?> cls) {
    if (cls.isArray()) {
        return isPrimitive(cls.getComponentType());
    }//from w w  w.jav a2  s. c  om
    return isPrimitive(cls);
}

From source file:com.l2jserver.util.transformer.impl.ArrayTransformer.java

@Override
@SuppressWarnings("unchecked")
public String transform(Class<? extends T[]> type, T[] value) {
    final Transformer<T> transformer = (Transformer<T>) TransformerFactory
            .getTransfromer(type.getComponentType());
    final String[] values = new String[value.length];
    int i = 0;/*from  w ww. j av  a  2 s . c om*/
    for (final T item : value) {
        values[i++] = transformer.transform((Class<T>) type.getComponentType(), item);
    }
    return StringUtils.join(values, '|');
}

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

/** Write a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *//*from   www  .ja va 2s. c o  m*/
public static void writeObject(DataOutput out, Object instance, Class declaredClass, CloudataConf conf,
        boolean arrayComponent) throws IOException {

    if (instance == null) { // null
        instance = new NullInstance(declaredClass, conf);
        declaredClass = CWritable.class;
        arrayComponent = false;
    }

    if (!arrayComponent) {
        CUTF8.writeString(out, declaredClass.getName()); // always write declared
        //System.out.println("Write:declaredClass.getName():" + declaredClass.getName());
    }

    if (declaredClass.isArray()) { // array
        int length = Array.getLength(instance);
        out.writeInt(length);
        //System.out.println("Write:length:" + length);

        if (declaredClass.getComponentType() == Byte.TYPE) {
            out.write((byte[]) instance);
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            //ColumnValue?  Deserialize? ?? ?   ?? ?  .
            writeColumnValue(out, instance, declaredClass, conf, length);
        } else {
            for (int i = 0; i < length; i++) {
                writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf,
                        !declaredClass.getComponentType().isArray());
            }
        }
    } else if (declaredClass == String.class) { // String
        CUTF8.writeString(out, (String) instance);

    } else if (declaredClass.isPrimitive()) { // primitive type

        if (declaredClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instance).booleanValue());
        } else if (declaredClass == Character.TYPE) { // char
            out.writeChar(((Character) instance).charValue());
        } else if (declaredClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instance).byteValue());
        } else if (declaredClass == Short.TYPE) { // short
            out.writeShort(((Short) instance).shortValue());
        } else if (declaredClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instance).intValue());
        } else if (declaredClass == Long.TYPE) { // long
            out.writeLong(((Long) instance).longValue());
        } else if (declaredClass == Float.TYPE) { // float
            out.writeFloat(((Float) instance).floatValue());
        } else if (declaredClass == Double.TYPE) { // double
            out.writeDouble(((Double) instance).doubleValue());
        } else if (declaredClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isEnum()) { // enum
        CUTF8.writeString(out, ((Enum) instance).name());
    } else if (CWritable.class.isAssignableFrom(declaredClass)) { // Writable
        if (instance.getClass() == declaredClass) {
            out.writeShort(TYPE_SAME); // ? ?? ? ?? 
            //System.out.println("Write:TYPE_SAME:" + TYPE_SAME);

        } else {
            out.writeShort(TYPE_DIFF);
            //System.out.println("Write:TYPE_DIFF:" + TYPE_DIFF);
            CUTF8.writeString(out, instance.getClass().getName());
            //System.out.println("Write:instance.getClass().getName():" + instance.getClass().getName());
        }
        ((CWritable) instance).write(out);
        //System.out.println("Write:instance value");

    } else {
        throw new IOException("Can't write: " + instance + " as " + declaredClass);
    }
}

From source file:com.metaparadigm.jsonrpc.ArraySerializer.java

@Override
public boolean canSerialize(Class clazz, Class jsonClazz) {
    Class cc = clazz.getComponentType();
    return (super.canSerialize(clazz, jsonClazz)
            || ((jsonClazz == null || jsonClazz == JSONArray.class) && (clazz.isArray() && !cc.isPrimitive())));
}

From source file:com.l2jserver.util.transformer.impl.ArrayTransformer.java

@Override
@SuppressWarnings("unchecked")
public T[] untransform(Class<? extends T[]> type, String stringValue) {
    final Transformer<T> transformer = (Transformer<T>) TransformerFactory
            .getTransfromer(type.getComponentType());
    final String[] stringValues = StringUtils.split(stringValue, '|');
    final Object values = Array.newInstance(type.getComponentType(), stringValues.length);
    int i = 0;//from   www .j a  va 2s  . c om
    for (final String value : stringValues) {
        Array.set(values, i++, transformer.untransform((Class<T>) type.getComponentType(), value));
    }

    return type.cast(values);
}

From source file:io.wcm.config.core.impl.ParameterOverrideProviderBridge.java

private String toJsonValue(String value, Class type) {
    if (type.isArray()) {
        return "[" + toJsonValue(value, type.getComponentType()) + "]";
    } else if (type == String.class) {
        return JSONObject.quote(value);
    } else if (type == int.class) {
        return Integer.toString(NumberUtils.toInt(value));
    } else if (type == long.class) {
        return Long.toString(NumberUtils.toLong(value));
    } else if (type == double.class) {
        return Double.toString(NumberUtils.toDouble(value));
    } else if (type == boolean.class) {
        return Boolean.toString(BooleanUtils.toBoolean(value));
    } else {//from  w  w  w .ja va  2s . c  om
        throw new IllegalArgumentException("Illegal value type: " + type.getName());
    }
}

From source file:grails.plugin.searchable.internal.compass.converter.DefaultCompassConverterLookupHelper.java

/**
 * Returns true if there is a registered Compass Converter for the given type
 * Also handles array types for supported array component types
 *
 * @param type a Class// w  w  w  .  j a va 2  s  .  co m
 * @return true if a converter is available
 */
public boolean hasConverter(Class type) {
    Assert.notNull(converterLookup, "converterLookup cannot be null");
    Assert.notNull(type, "type cannot be null");
    if (type.isArray()) {
        type = type.getComponentType();
    }
    return converterLookup.lookupConverter(type) != null;
}

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * /*from www  . java  2s . c  om*/
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:jef.tools.ArrayUtils.java

/**
 * @since JDK 1.6/*from  w  ww .j  av a2 s.  c om*/
 */
@SuppressWarnings("unchecked")
public final static <T, U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
    return copy;
}

From source file:net.buffalo.protocal.util.ClassUtil.java

public static Object convertValue(Object value, Class targetType) {

    if (value.getClass().equals(targetType))
        return value;

    if (targetType.isPrimitive()) {
        targetType = getWrapperClass(targetType);
    }/*from  ww  w.j  ava  2s .  c om*/

    if (targetType.isAssignableFrom(value.getClass()))
        return value;

    if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) {
        try {
            Constructor ctor = targetType.getConstructor(new Class[] { String.class });
            return ctor.newInstance(new Object[] { value.toString() });
        } catch (Exception e) {
            LOGGER.error("convert type error", e);
            throw new RuntimeException(
                    "Cannot convert from " + value.getClass().getName() + " to " + targetType, e);
        }
    }

    if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) {
        Collection collection = (Collection) value;
        Object array = Array.newInstance(targetType.getComponentType(), collection.size());
        int i = 0;
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object val = iter.next();
            Array.set(array, i++, val);
        }

        return array;
    }

    if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) {
        return Arrays.asList((Object[]) value);
    }

    throw new IllegalArgumentException(
            "Cannot convert from " + value.getClass().getName() + " to " + targetType);
}