Reputation: 501
I'm reviewing code that features this construction. MyClass
is the name of a class. Why would a someone use
String name = MyClass.class.getName();
instead of
String name = "MyClass";
given that the class name is already identified in the former? Is there something I'm missing?
Upvotes: 3
Views: 2278
Reputation: 86411
The method getName()
:
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++.
Upvotes: 2
Reputation: 280898
If you accidentally spell the first one MyClas.class.getName()
, it won't compile. The second one will.
Also, as JB Nizet points out, getName
includes the full package hierarchy in the name. For example, if MyClass
is under the com.piotrchernin
package, MyClass.class.getName()
will be "com.piotrchernin.MyClass"
, not "MyClass"
.
Upvotes: 7
Reputation: 50041
If the class is later renamed, then the MyClass.class.getName()
reference will need to be checked and fixed up in order to compile (or will be fixed up automatically by the IDE). The string will not, which means it will compile correctly, but not actually work correctly, which is worse because it hides the problem.
Referring to the class name this way is an application of the Don't Repeat Yourself principle.
Upvotes: 8