DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Java: Getting The Name Of A Class Object

05.17.2007
| 10049 views |
  • submit to reddit
        // Ref: http://www.exampledepot.com/egs/java.lang/GetClassName.html

    // Get the fully-qualified name of a class
    Class cls = java.lang.String.class;
    String name = cls.getName();        // java.lang.String
    
    // Get the fully-qualified name of a inner class
    cls = java.util.Map.Entry.class;
    name = cls.getName();               // java.util.Map$Entry
    
    // Get the unqualified name of a class
    cls = java.util.Map.Entry.class;
    name = cls.getName();
    if (name.lastIndexOf('.') > 0) {
        name = name.substring(name.lastIndexOf('.')+1);  // Map$Entry
    }
    // The $ can be converted to a .
    name = name.replace('$', '.');      // Map.Entry
    
    
    // Get the name of a primitive type
    name = int.class.getName();         // int
    
    // Get the name of an array
    name = boolean[].class.getName();   // [Z
    name = byte[].class.getName();      // [B
    name = char[].class.getName();      // [C
    name = short[].class.getName();     // [S
    name = int[].class.getName();       // [I
    name = long[].class.getName();      // [J
    name = float[].class.getName();     // [F
    name = double[].class.getName();    // [D
    name = String[].class.getName();    // [Ljava.lang.String;
    name = int[][].class.getName();     // [[I
    
    // Get the name of void
    cls = Void.TYPE;
    name = cls.getName();               // void