Java Class Name Create toClassName(Object obj)

Here you can find the source of toClassName(Object obj)

Description

Returns the name of the class of the object in a short and readable form.

License

Open Source License

Parameter

Parameter Description
obj the object, may be null

Return

the name

Declaration

public static String toClassName(Object obj) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w  w w  .j a  v a 2 s. co m
     * Returns the name of the class of the object in a short and readable form.
     *
     * @param obj the object, may be null
     * @return the name
     */
    public static String toClassName(Object obj) {
        if (obj == null) {
            return toClassName(Void.class);
        }

        return toClassName(obj.getClass());
    }

    /**
     * Returns the name of the class in a short and readable form.
     *
     * @param type the class, may be null
     * @return the name
     */
    public static String toClassName(Class<?> type) {
        if (type == null) {
            return "?";
        }

        String name = "";

        while (type.isArray()) {
            name = "[]" + name;
            type = type.getComponentType();
        }

        if (type.isPrimitive()) {
            name = type.getName() + name;
        } else {
            name = getShortName(type.getName()) + name;
        }

        return name;
    }

    private static String getShortName(String currentName) {
        int beginIndex = currentName.lastIndexOf('.');

        if (beginIndex >= 0) {
            currentName = currentName.substring(beginIndex + 1);
        }

        return currentName;
    }
}

Related

  1. toClassName(Class clazz)
  2. toClassName(Enum enumeration)
  3. toClassname(String apparatClassname)
  4. toClassName(String className)
  5. toClassName(String className)
  6. toClassName(String className)