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.
getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.
You can use this idiom
Class<?> cl=new Object(){}.getClass().getEnclosingClass();
For example:
static class Bar { public static void main(String[] args) { Class<?> cl=new Object(){}.getClass().getEnclosingClass(); System.out.println(cl==Bar.class); //will print true } }
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