Reputation: 113
what is the advantage of using Class.getSimpleName()
, instead of hardcoding the class name in java?
Upvotes: 5
Views: 2813
Reputation: 17
The java.lang.Class.getSimpleName() returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.
so as Kocko said "Class.getSimpleName() will always return you the name without any typos, while you can make a typo hardcoding the class name." and as sᴜʀᴇsʜ ᴀᴛᴛᴀ said "When you re-factor your Class name later, the hardcoded name won't change and the getSimpleName() always gives you the current Class name." and so you can keep making changes and refracting the class without being worried of creating error in dependent classes.
Upvotes: 0
Reputation: 122006
When you re-factor your Class name later, the hardcoded name won't change and the getSimpleName()
always gives you the current Class name.
You always need to remember the places to change if you hard code the class name while updating the Class name.
Not only Class name, avoid hard coding AMAP. Otherwise it really increase the cost of maintenance.
Upvotes: 2
Reputation: 62864
Class.getSimpleName()
will always return you the name without any typos, while hardcoding the class name can lead to a typo.
If you change the class name, Class.getSimpleName()
will return the updated name, while the hardcoded one won't change.
Upvotes: 8