Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't getClass() available as a static method?

Tags:

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.

like image 360
Jason S Avatar asked Apr 20 '11 16:04

Jason S


People also ask

What does getClass () do in Java?

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.

Why static method do not get this reference?

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.

What does getClass () getName () Do Java?

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.


1 Answers

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     } } 
like image 184
alexsmail Avatar answered Oct 12 '22 04:10

alexsmail