In static contexts, how come you can't call a static version of getClass()
(rather than having to use my.package.name.MyClassName.class
) ?
Isn't the compiler smart enough to determine when to use object methods + when to use static methods?
NOTE for clarity:
I'm not saying that a static getClass()
should be used instead of the non-static method getClass()
(that's kind of obvious -- if SpecialFoo
is a subclass of Foo
, then the getClass()
of a Foo
could return Foo.class
or SpecialFoo.class
or something else and it has to be determined at runtime).
I'm saying that I'm wondering why aren't there two versions of getClass()
, one that is a static method which only applies in a static context, and the regular non-static method getClass()
. If it's not possible, then it's not possible, and that's the answer. If it's possible but just hasn't been done, then it's a historical choice, and maybe there's a good reason for it. That's what I'd like to know.
It would be great to declare
final static Logger logger = LoggerFactory.getLogger(getClass());
instead of
final static Logger logger = LoggerFactory.getLogger(my.package.name.MyClass.class);
where the former could be copied verbatim from one class to the next, whereas the latter requires you to copy the class name in each file.
Each object is an instance of a class in Java and no class can be an instance of another class! Which is why getClass() is not static as it only makes sense in the context of an object : you are trying to find for an object what class is it an instance of. If it was a static function, it can be called outside an object -- but it doesn't make sense to write
because you already know you're "asking" the String class!
Wouldn't a static
getClass()
method return the class object the class the variable which holds the object is from? That would change the semantics ofgetClass()
. Example:If nothing else, because it isn't legal to have both a
static
and non-static
version of a method (probably because it's legal, if discouraged, to call astatic
method in a non-static
context).I also feel like such a method, while useful in the context of defining a logger or whatever, could be confusing in other contexts, such as when called from an instance method.
Because if
getClass()
would be static, its code would have to be defined in one class - probablyObject
. There, you can't determine the callers class and there isn't an object instance who calls it.Edit:
It's not about the name; it could be very well
getClass2()
. I'm saying that if you define a static method, you can't know the class that calls it:You can use this idiom
For example:
You can implement one yourself. Get the stacktrace, and find the caller class.
Actually the logger lib could implemented that itself