In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:
public class MyClass {
private static final String CLASS_NAME = MyClass.class.getName();
//...
}
What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName()
call directly where the name is needed?
Here is the implementation of Class.getName()
public String getName() {
if (name == null)
name = getName0();
return name;
}
As you can see the value of name is cached, so the call is not too expensive. It is just as call of regular getter. Anyway if you call it very often it is probably a good style to define constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With