Java Class Name Extract extractClassName(final String fullClassName)

Here you can find the source of extractClassName(final String fullClassName)

Description

Extract the name of a class from the full name (includes packages).

License

Open Source License

Parameter

Parameter Description
fullClassName class name including packages

Return

name of the class

Declaration

public static String extractClassName(final String fullClassName) 

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
     * The beginning delimiter of generics. E.g., List<Object> uses < as the beginning delimiter.
     */
    private static final String GENERICS_START = "<";

    /**
     * Extract the name of a class from the full name (includes packages).
     * (Without generics and parent)
     * @param fullClassName class name including packages
     * @return name of the class
     */
    public static String extractClassName(final String fullClassName) {
        return extractClassNameWithGeneric(fullClassName).replaceAll(
                "<(.*)>", "");
    }

    /**
     * Extract class name with generics.
     * @param fullClassName class name including packages
     * @return name of class with generics.
     */
    public static String extractClassNameWithGeneric(
            final String fullClassName) {
        String[] genericSplit = fullClassName.split(GENERICS_START);
        String[] splitName = genericSplit[0].split("\\.");
        String generic = extractGeneric(fullClassName);
        if (!generic.isEmpty()) {
            generic = GENERICS_START + generic + ">";
        }
        return splitName[Math.max(splitName.length - 1, 0)] + generic;
    }

    /**
     * Extract only the generic type parameters of a class.
     * @param fullClassName class name including packages
     * @return generic type parameters of class.
     */
    public static String extractGeneric(final String fullClassName) {
        String[] splitGeneric = fullClassName.replaceAll("\\$", ".").trim()
                .split(GENERICS_START);
        String genericPart = "";
        if (splitGeneric.length > 1) {
            for (int i = 1; i < splitGeneric.length; i++) {
                genericPart += splitGeneric[i];
                if (i != splitGeneric.length) {
                    genericPart += GENERICS_START;
                }
            }
            genericPart = extractClassNameWithGeneric(genericPart
                    .substring(0, genericPart.length() - 2));
        }
        return genericPart;
    }
}

Related

  1. extractClassName(final String classPath)
  2. extractClassName(String fullClassName)
  3. extractClassName(String fullElement)
  4. extractClassName(String fullyQualifiedClassName)
  5. extractClassName(String javaSource)