Java Class Name Get className(Class type)

Here you can find the source of className(Class type)

Description

Returns the class formatted as a string.

License

Open Source License

Declaration

static public String className(Class type) 

Method Source Code

//package com.java2s;

public class Main {
    /** Returns the class formatted as a string. The format varies depending on the type. */
    static public String className(Class type) {
        if (type.isArray()) {
            Class elementClass = getElementClass(type);
            StringBuilder buffer = new StringBuilder(16);
            for (int i = 0, n = getDimensionCount(type); i < n; i++)
                buffer.append("[]");
            return className(elementClass) + buffer;
        }//from ww w  .  ja v a2  s.  c  om
        if (type.isPrimitive() || type == Object.class || type == Boolean.class || type == Byte.class
                || type == Character.class || type == Short.class || type == Integer.class || type == Long.class
                || type == Float.class || type == Double.class || type == String.class) {
            return type.getSimpleName();
        }
        return type.getName();
    }

    /** Returns the base element type of an n-dimensional array class. */
    static public Class getElementClass(Class arrayClass) {
        Class elementClass = arrayClass;
        while (elementClass.getComponentType() != null)
            elementClass = elementClass.getComponentType();
        return elementClass;
    }

    /** Returns the number of dimensions of an array. */
    static public int getDimensionCount(Class arrayClass) {
        int depth = 0;
        Class nextClass = arrayClass.getComponentType();
        while (nextClass != null) {
            depth++;
            nextClass = nextClass.getComponentType();
        }
        return depth;
    }
}

Related

  1. classname(Class javaClass)
  2. className(Class aClass)
  3. className(final Class c)
  4. className(final Object object)
  5. className(Object o)