generic way of getting class name
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.
Not sure if I understand your question - did you try this.getClass().getCanonicalName()
?
There is a horrible hack
class MyClass{
private static String cannonicalName;
static{
cannonicalName = new Object(){}.getEnclosingClass().getCannonicalName();
}
}
Is that what you're looking for? It does give you the class name in a generic and static way, but you create an anonymous class just for it.
I think what you're trying to do is this:
public static <T> String getCanonicalName() {
return T.class.getCanonicalName();
}
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, T
only exists at compile time. At run time, T
is 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
static String ClassName = Thread.currentThread().getStackTrace[0].getClassName();
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 of getClassName()
into the output of getCanonicalName()
.
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 self
keyword to could be added refer to the current class it would simplify any scenario like yours, by allowing you to write things like self.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:
static String ClassName = null;
public Foo() {
if(ClassName == null)
ClassName = this.getClass().getCanonicalName();
}
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 self
keyword.
Not quite understanding what you mean, perhaps this is what you are after:
public static String getCanonicalName(Class<?> clazz){
return clazz.getCanonicalName();
}
精彩评论