Example usage for java.lang Character TYPE

List of usage examples for java.lang Character TYPE

Introduction

In this page you can find the example usage for java.lang Character TYPE.

Prototype

Class TYPE

To view the source code for java.lang Character TYPE.

Click Source Link

Document

The Class instance representing the primitive type char .

Usage

From source file:agilejson.JSON.java

/**
 * Work Horse of the library//from w ww . j av a 2 s.  c o  m
 * @param o
 * @param alreadyVisited
 * @return Proper Json String
 * @throws org.json.JSONException
 * @throws java.lang.IllegalAccessException
 */
protected static String toJSON(Object o, Set alreadyVisited) throws JSONException, IllegalAccessException {

    // If null return JSON's null value, null
    if (o == null) {
        return "null";
    }

    // Get class for reflection purposes
    Class c = o.getClass();

    // Make sure that given a primitive, it is not added to already visited
    // This is for two reasons:
    // 1. Classes are sealed so can not point to other objects.
    // 2. String, et. al., have overridden equals methods which is true
    //     given equality of value, not equality of reference.
    // This results in the loss of values in the json representation
    if (!PRIMITIVES.contains(c)) {
        alreadyVisited.add(o);
    }

    // Use no excape stringer b/c we want to escape strings only once,
    // to stop things like \\\\\\n, etc.
    JSONStringer s = new NoEscapesStringer();

    // If Array handle elements
    if ((Object[].class).isAssignableFrom(c)) {
        if ((Byte[].class).isAssignableFrom(c)) {
            Byte[] B = (Byte[]) o;
            byte[] b = new byte[B.length];
            for (int i = 0; i < B.length; i++) {
                if (B[i] != null)
                    b[i] = B[i].byteValue();
                else
                    b[i] = 48;
            }
            return "\"" + escape(new String(b)) + "\"";
        } else if ((Character[].class).isAssignableFrom(c)) {
            Character[] C = (Character[]) o;
            char[] primitiveC = new char[C.length];
            for (int i = 0; i < C.length; i++) {
                if (C[i] != null)
                    primitiveC[i] = C[i].charValue();
                else
                    primitiveC[i] = '0';
            }
            return "\"" + escape(new String(primitiveC)) + "\"";
        } else {
            jsonifyArray(o, s, alreadyVisited);
        }
    } else {
        // Check this part
        if (PRIMITIVEARRAYS.contains(c)) {
            // If byte/char array return as a string. Otherwise returns
            // as a space delimited Hex Representation of the bytes
            if ((byte[].class).isAssignableFrom(c)) {
                try {
                    return "\"" + escape(new String((byte[]) o, "UTF-8")) + "\"";
                } catch (UnsupportedEncodingException ex) {
                    return "\"" + escape(new String((byte[]) o)) + "\"";
                }
            } else if ((char[].class).isAssignableFrom(c)) {
                return "\"" + escape(new String((char[]) o)) + "\"";
            } else {
                s.array();
                if ((short[].class).isAssignableFrom(c)) {
                    short[] array = (short[]) o;
                    for (short b : array) {
                        s.value(String.valueOf(b));
                    }
                } else if ((int[].class).isAssignableFrom(c)) {
                    int[] array = (int[]) o;
                    for (int b : array) {
                        s.value(String.valueOf(b));
                    }
                } else if ((long[].class).isAssignableFrom(c)) {
                    long[] array = (long[]) o;
                    for (long b : array) {
                        s.value(String.valueOf(b));
                    }
                } else if ((float[].class).isAssignableFrom(c)) {
                    float[] array = (float[]) o;
                    for (float b : array) {
                        s.value(String.valueOf(b));
                    }
                } else if ((double[].class).isAssignableFrom(c)) {
                    double[] array = (double[]) o;
                    for (double b : array) {
                        s.value(String.valueOf(b));
                    }
                } else {
                    boolean[] array = (boolean[]) o;
                    for (boolean b : array) {
                        s.value(String.valueOf(b));
                    }
                }
                s.endArray();
            }
        } else if (String.class.isAssignableFrom(c) || (Character.TYPE).isAssignableFrom(c)
                || (Character.class).isAssignableFrom(c)) {
            return '"' + escape(o.toString()) + '"';
        } else if (PRIMITIVES.contains(c) || JSONObject.class.isAssignableFrom(c)
                || JSONArray.class.isAssignableFrom(c)) {
            return o.toString();
        } else {
            // Note json object is created inside jsonify getters
            // this is because we dont know whether or not we have
            // methods which are annotated as @TOJSON until we get in there.
            // This allows us to just tostring the output if no methods
            // have been annotated.
            Method[] m = c.getMethods();
            if (m.length != 0) {
                if (!jsonifyGetters(o, m, s, alreadyVisited)) {
                    return "\"" + escape(o.toString()) + "\"";
                }
            } else {
                return "\"" + escape(o.toString()) + "\"";
            }
        }
    }
    return s.toString();
}

From source file:org.pentaho.reporting.engine.classic.core.util.beans.BeanUtility.java

public static boolean isSameType(final Class declared, final Class object) {
    if (declared.equals(object)) {
        return true;
    }//from  w  ww .j  av  a2 s  .  c om

    if (Float.TYPE.equals(declared) && Float.class.equals(object)) {
        return true;
    }
    if (Double.TYPE.equals(declared) && Double.class.equals(object)) {
        return true;
    }
    if (Byte.TYPE.equals(declared) && Byte.class.equals(object)) {
        return true;
    }
    if (Character.TYPE.equals(declared) && Character.class.equals(object)) {
        return true;
    }
    if (Short.TYPE.equals(declared) && Short.class.equals(object)) {
        return true;
    }
    if (Integer.TYPE.equals(declared) && Integer.class.equals(object)) {
        return true;
    }
    if (Long.TYPE.equals(declared) && Long.class.equals(object)) {
        return true;
    }
    return false;
}

From source file:org.crank.javax.faces.component.MenuRenderer.java

protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class<?> arrayClass,
        String[] newValues) throws ConverterException {

    Object result = null;//  ww  w .  j a  v a2  s  .c  o  m
    Converter converter = null;
    int len = (null != newValues ? newValues.length : 0);

    Class<?> elementType = arrayClass.getComponentType();

    // Optimization: If the elementType is String, we don't need
    // conversion.  Just return newValues.
    if (elementType.equals(String.class)) {
        return newValues;
    }

    try {
        result = Array.newInstance(elementType, len);
    } catch (Exception e) {
        throw new ConverterException(e);
    }

    // bail out now if we have no new values, returning our
    // oh-so-useful zero-length array.
    if (null == newValues) {
        return result;
    }

    // obtain a converter.

    // attached converter takes priority
    if (null == (converter = uiSelectMany.getConverter())) {
        // Otherwise, look for a by-type converter
        if (null == (converter = Util.getConverterForClass(elementType, context))) {
            // if that fails, and the attached values are of Object type,
            // we don't need conversion.
            if (elementType.equals(Object.class)) {
                return newValues;
            }
            StringBuffer valueStr = new StringBuffer();
            for (int i = 0; i < len; i++) {
                if (i == 0) {
                    valueStr.append(newValues[i]);
                } else {
                    valueStr.append(' ').append(newValues[i]);
                }
            }
            Object[] params = { valueStr.toString(), "null Converter" };

            throw new ConverterException(
                    MessageUtils.getExceptionMessage(MessageUtils.CONVERSION_ERROR_MESSAGE_ID, params));
        }
    }

    assert (null != result);
    if (elementType.isPrimitive()) {
        for (int i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])));
            }
        }
    } else {
        for (int i = 0; i < len; i++) {
            if (logger.isLoggable(Level.FINE)) {
                Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]);
                logger.fine("String value: " + newValues[i] + " converts to : " + converted.toString());
            }
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
        }
    }
    return result;

}

From source file:Main.java

/**
 * <p>Inserts the specified element at the specified position in the array.
 * Shifts the element currently at that position (if any) and any subsequent
 * elements to the right (adds one to their indices).</p>
 *
 * <p>This method returns a new array with the same elements of the input
 * array plus the given element on the specified position. The component
 * type of the returned array is always the same as that of the input
 * array.</p>/*from  ww w . ja v a 2  s  . c o  m*/
 *
 * <p>If the input array is {@code null}, a new one element array is returned
 *  whose component type is the same as the element.</p>
 *
 * <pre>
 * ArrayUtils.add(null, 0, 'a')            = ['a']
 * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']
 * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']
 * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']
 * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']
 * </pre>
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @return A new array containing the existing elements and the new element
 * @throws IndexOutOfBoundsException if the index is out of range
 * (index < 0 || index > array.length).
 */
public static char[] add(final char[] array, final int index, final char element) {
    return (char[]) add(array, index, Character.valueOf(element), Character.TYPE);
}

From source file:org.jfree.chart.demo.SymbolicXYPlotDemo.java

/**
 * Transform an primitive array to an object array.
 * //from  www.ja  va2 s  .  c o m
 * @param arr
 *           the array.
 * @return an array.
 */
private static Object toArray(final Object arr) {

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

    final Class cls = arr.getClass();
    if (!cls.isArray()) {
        return arr;
    }

    Class compType = cls.getComponentType();
    int dim = 1;
    while (!compType.isPrimitive()) {
        if (!compType.isArray()) {
            return arr;
        } else {
            dim++;
            compType = compType.getComponentType();
        }
    }

    final int[] length = new int[dim];
    length[0] = Array.getLength(arr);
    Object[] newarr = null;

    try {
        if (compType.equals(Integer.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length);
        } else if (compType.equals(Double.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length);
        } else if (compType.equals(Long.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length);
        } else if (compType.equals(Float.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length);
        } else if (compType.equals(Short.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length);
        } else if (compType.equals(Byte.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length);
        } else if (compType.equals(Character.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length);
        } else if (compType.equals(Boolean.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length);
        }
    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    }

    for (int i = 0; i < length[0]; i++) {
        if (dim != 1) {
            newarr[i] = toArray(Array.get(arr, i));
        } else {
            newarr[i] = Array.get(arr, i);
        }
    }
    return newarr;
}

From source file:org.enerj.apache.commons.beanutils.ConvertUtilsBean.java

/**
 * Remove all registered {@link Converter}s, and re-establish the
 * standard Converters.//from w w w. ja v  a  2  s  . c  o m
 */
public void deregister() {

    boolean booleanArray[] = new boolean[0];
    byte byteArray[] = new byte[0];
    char charArray[] = new char[0];
    double doubleArray[] = new double[0];
    float floatArray[] = new float[0];
    int intArray[] = new int[0];
    long longArray[] = new long[0];
    short shortArray[] = new short[0];
    String stringArray[] = new String[0];

    converters.clear();
    register(BigDecimal.class, new BigDecimalConverter());
    register(BigInteger.class, new BigIntegerConverter());
    register(Boolean.TYPE, new BooleanConverter(defaultBoolean));
    register(Boolean.class, new BooleanConverter(defaultBoolean));
    register(booleanArray.getClass(), new BooleanArrayConverter(booleanArray));
    register(Byte.TYPE, new ByteConverter(defaultByte));
    register(Byte.class, new ByteConverter(defaultByte));
    register(byteArray.getClass(), new ByteArrayConverter(byteArray));
    register(Character.TYPE, new CharacterConverter(defaultCharacter));
    register(Character.class, new CharacterConverter(defaultCharacter));
    register(charArray.getClass(), new CharacterArrayConverter(charArray));
    register(Class.class, new ClassConverter());
    register(Double.TYPE, new DoubleConverter(defaultDouble));
    register(Double.class, new DoubleConverter(defaultDouble));
    register(doubleArray.getClass(), new DoubleArrayConverter(doubleArray));
    register(Float.TYPE, new FloatConverter(defaultFloat));
    register(Float.class, new FloatConverter(defaultFloat));
    register(floatArray.getClass(), new FloatArrayConverter(floatArray));
    register(Integer.TYPE, new IntegerConverter(defaultInteger));
    register(Integer.class, new IntegerConverter(defaultInteger));
    register(intArray.getClass(), new IntegerArrayConverter(intArray));
    register(Long.TYPE, new LongConverter(defaultLong));
    register(Long.class, new LongConverter(defaultLong));
    register(longArray.getClass(), new LongArrayConverter(longArray));
    register(Short.TYPE, new ShortConverter(defaultShort));
    register(Short.class, new ShortConverter(defaultShort));
    register(shortArray.getClass(), new ShortArrayConverter(shortArray));
    register(String.class, new StringConverter());
    register(stringArray.getClass(), new StringArrayConverter(stringArray));
    register(Date.class, new SqlDateConverter());
    register(Time.class, new SqlTimeConverter());
    register(Timestamp.class, new SqlTimestampConverter());
    register(File.class, new FileConverter());
    register(URL.class, new URLConverter());

}

From source file:org.apache.struts2.jasper.compiler.JspUtil.java

/**
 * Produces a String representing a call to the EL interpreter.
 *
 * @param isTagFile    is a tag file//from  w  w  w  . j  a v  a 2s  .  c om
 * @param expression   a String containing zero or more "${}" expressions
 * @param expectedType the expected type of the interpreted result
 * @param fnmapvar     Variable pointing to a function map.
 * @param XmlEscape    True if the result should do XML escaping
 * @return a String representing a call to the EL interpreter.
 */
public static String interpreterCall(boolean isTagFile, String expression, Class expectedType, String fnmapvar,
        boolean XmlEscape) {
    /*
     * Determine which context object to use.
     */
    String jspCtxt = null;
    if (isTagFile)
        jspCtxt = "this.getJspContext()";
    else
        jspCtxt = "_jspx_page_context";

    /*
         * Determine whether to use the expected type's textual name
     * or, if it's a primitive, the name of its correspondent boxed
     * type.
         */
    String targetType = expectedType.getName();
    String primitiveConverterMethod = null;
    if (expectedType.isPrimitive()) {
        if (expectedType.equals(Boolean.TYPE)) {
            targetType = Boolean.class.getName();
            primitiveConverterMethod = "booleanValue";
        } else if (expectedType.equals(Byte.TYPE)) {
            targetType = Byte.class.getName();
            primitiveConverterMethod = "byteValue";
        } else if (expectedType.equals(Character.TYPE)) {
            targetType = Character.class.getName();
            primitiveConverterMethod = "charValue";
        } else if (expectedType.equals(Short.TYPE)) {
            targetType = Short.class.getName();
            primitiveConverterMethod = "shortValue";
        } else if (expectedType.equals(Integer.TYPE)) {
            targetType = Integer.class.getName();
            primitiveConverterMethod = "intValue";
        } else if (expectedType.equals(Long.TYPE)) {
            targetType = Long.class.getName();
            primitiveConverterMethod = "longValue";
        } else if (expectedType.equals(Float.TYPE)) {
            targetType = Float.class.getName();
            primitiveConverterMethod = "floatValue";
        } else if (expectedType.equals(Double.TYPE)) {
            targetType = Double.class.getName();
            primitiveConverterMethod = "doubleValue";
        }
    }

    if (primitiveConverterMethod != null) {
        XmlEscape = false;
    }

    /*
         * Build up the base call to the interpreter.
         */
    // XXX - We use a proprietary call to the interpreter for now
    // as the current standard machinery is inefficient and requires
    // lots of wrappers and adapters.  This should all clear up once
    // the EL interpreter moves out of JSTL and into its own project.
    // In the future, this should be replaced by code that calls
    // ExpressionEvaluator.parseExpression() and then cache the resulting
    // expression objects.  The interpreterCall would simply select
    // one of the pre-cached expressions and evaluate it.
    // Note that PageContextImpl implements VariableResolver and
    // the generated Servlet/SimpleTag implements FunctionMapper, so
    // that machinery is already in place (mroth).
    targetType = toJavaSourceType(targetType);
    StringBuilder call = new StringBuilder(
            "(" + targetType + ") " + "org.apache.struts2.jasper.runtime.PageContextImpl.proprietaryEvaluate"
                    + "(" + Generator.quote(expression) + ", " + targetType + ".class, " + "(PageContext)"
                    + jspCtxt + ", " + fnmapvar + ", " + XmlEscape + ")");

    /*
         * Add the primitive converter method if we need to.
         */
    if (primitiveConverterMethod != null) {
        call.insert(0, "(");
        call.append(")." + primitiveConverterMethod + "()");
    }

    return call.toString();
}

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.//from w  w  w . j  a v  a2s  .c o  m
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else if (Scan.class.isAssignableFrom(declClass)) {
        Scan scan = (Scan) instanceObj;
        byte[] scanBytes = ProtobufUtil.toScan(scan).toByteArray();
        out.writeInt(scanBytes.length);
        out.write(scanBytes);
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.// w  ww  . ja v a  2s  . co  m
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else if (declClass.equals(Result[].class)) {
            Result.writeArray(out, (Result[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:au.gov.ansto.bragg.kowari.ui.views.AnalysisControlView.java

private String getDeviceInfo(Plot inputdata, String deviceName, String numericFormat, int index) {
    String result = "";
    if (deviceName != null) {
        try {/*from  w  w  w .  j  av  a  2s  .  c o m*/
            Object item = inputdata.getContainer(deviceName);
            if (item == null)
                item = inputdata.getContainer("old_" + deviceName);
            IArray signal = null;
            String units = "";
            if (item instanceof IDataItem) {
                signal = ((IDataItem) item).getData();
                units = ((IDataItem) item).getUnitsString();
            } else if (item instanceof IAttribute)
                signal = ((IAttribute) item).getValue();
            if (signal.getElementType() == Character.TYPE)
                result = signal.toString();
            else {
                double signalMax = signal.getArrayMath().getMaximum();
                double signalMin = signal.getArrayMath().getMinimum();
                //               result = deviceName + "=";
                if (numericFormat == null)
                    numericFormat = "%.5f";
                if (signalMax == signalMin)
                    result += (new Formatter()).format(numericFormat, signalMax) + " ";
                else
                    result += (new Formatter()).format(numericFormat,
                            signal.getDouble(signal.getIndex().set(index))) + " ";
            }
        } catch (Exception e) {
        }
    }
    return result;
}