The method getName():
- Works for code that has a Class object, but does not know the actual class.
- Continues to work after the class has been renamed.
- Works on Class objects representing arrays.
Code that does not know the class
As you note, one way to obtain a Class object is MyClass.class. However, it is not the only way. You can also call the method getClass() on an object of a class -- even in code that's referring to the object via an interface or superclass type. And some code receives a Class object from a caller.
As an example of the former, consider the following class hierarchy and factory method:
public interface IFoo { } public class AlphaFoo implements IFoo {} public class BetaFoo implements IFoo {} public FooFactory { public static IFoo makeFoo() { ... } }
The caller of the factory does not know what kind of IFoo will be returned. If you wanted to debug-print the actual class received from the factory, you could do this:
IFoo foo = FooFactory.makeFoo(); System.out.println( foo.getClass().getName() );
Refactoring
As an example of resilience to refactoring, consider this creation of a standard Java logger:
public class Bar { private static final Logger s_logger = Logger.getLogger( Bar.class.getName() ); ... }
If I rename the class using my IDE's refactoring tools, the logger name will update automatically.
Arrays
You can call getName() on a Class object representing an array.
String[] strs = new String[] { "alpha", "beta", "gamma" }; System.out.println( strs.getClass().getName() );
The output is:
[Ljava.lang.String;
Now, you might ask how this is useful. This syntax turns out to be how array arguments are expressed in calls to the JNI method GetMethodID(), which is necessary to call Java methods from C/C++.
getName()method allows you to get the name of the specific class represented.