Java Object to String toString(Object object, Class objectClass)

Here you can find the source of toString(Object object, Class objectClass)

Description

to String

License

Apache License

Declaration

public static String toString(Object object, Class<?> objectClass) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Arrays;

public class Main {
    public static String toString(Object object, Class<?> objectClass) {
        if (null == object) {
            return "null";
        }//from w  w  w .j a  v  a  2s  .  c o m
        final String toString = object.toString();
        if (isStringEmpty(toString)) {
            return "\"\"";
        } else if (String.class.equals(objectClass)) {
            return "\"" + toString + '\"';
        } else {
            return toString;
        }
    }

    /**
     * Returns the string representation of the specified object, transparently
     * handling null references and arrays.
     * 
     * @param obj
     *            the object
     * @return the string representation
     */
    public static String toString(Object obj) {
        String result;
        if (obj != null) {
            if (obj instanceof boolean[]) {
                result = Arrays.toString((boolean[]) obj);
            } else if (obj instanceof byte[]) {
                result = Arrays.toString((byte[]) obj);
            } else if (obj instanceof char[]) {
                result = Arrays.toString((char[]) obj);
            } else if (obj instanceof double[]) {
                result = Arrays.toString((double[]) obj);
            } else if (obj instanceof float[]) {
                result = Arrays.toString((float[]) obj);
            } else if (obj instanceof int[]) {
                result = Arrays.toString((int[]) obj);
            } else if (obj instanceof long[]) {
                result = Arrays.toString((long[]) obj);
            } else if (obj instanceof Object[]) {
                result = Arrays.deepToString((Object[]) obj);
            } else if (obj instanceof short[]) {
                result = Arrays.toString((short[]) obj);
            } else {
                result = obj.toString();
            }
        } else {
            result = "null";
        }
        return result;
    }

    public static boolean isStringEmpty(String s) {
        return s == null || "".equals(s);
    }
}

Related

  1. toString(Object obj)
  2. toString(Object object)
  3. toString(Object object)
  4. toString(Object object)
  5. toString(Object object)
  6. toString(Object val)
  7. toString(Object value)
  8. toString(Object value)
  9. toString(Object value)