Would what be a static equivalent of a dynamic
String CLASS_NAME = this.getClass().getCanonicalName()
Note that the following is not what i’m looking for since it specifically refers to a particular class. I’d like to refer to class name outside of a method (ie in the static {} section)
static String CLASS_NAME = Foo.class.getCanonicalName()
THanks.
I think what you’re trying to do is this:
But I’m sure that you’ve already figured out that this does not work. This is because Java generics rely on type erasure. That is,
Tonly exists at compile time. At run time,Tis no longer accessible.To do this generically, you must use an instance of the type as you did in your first example.
Edit
After realizing the true nature of your question, I do not come bearing a direct answer.
I have seen certain “hacks” like the following
This gets the name of the class, but I’m pretty sure it will not be the same as that returned by
getCanonicalName(), and I really don’t know of a way to transform the output ofgetClassName()into the output ofgetCanonicalName().I think it there are is a change to the Java language that would have really helped developers write intuitive code: if some sort of
selfkeyword to could be added refer to the current class it would simplify any scenario like yours, by allowing you to write things likeself.class.getCanonicalName(). But, as things stand, we don’t have that, so what you’d like to do isn’t directly possible.There are other possible workarounds. For example, you can try something like:
But that requires your class to be constructible, which is not always desirable. It’s also not nearly as straightforward as it could be if we had a
selfkeyword.