How to call getClass() from a static method in Java?
To reference a class from a static context, use ClassName.class
in lieu of getClass()
, which is unavailable statically. Here's how you access the Class
object for MyClass
:
Class literals: Saving the day
ClassName.class
isn't merely a substitute for getClass()
. It brings efficiency by resolving class literals at compile time, eliminating runtime overhead.
Secure your Logger: Pro tips
To declare Logger
instances, use IntelliJ IDEA's powerful Live Templates. Try this: set "log" as an abbreviation and enjoy className()
auto-inserting the class name. A bonus: it performs import optimization and code reformat on expansion.
No getClass()? No problem
In a static method, getClass()
won't help to access resources. But MyClass.class.getResource()
and Thread.currentThread().getContextClassLoader()
will.
Beware the anonymous subclass
Desperate times call for desperate measures, like the anonymous subclass trick. But remember, with great power...
...comes potential memory leaks. Stick to class literals when possible.
Advanced techniques: Handle with care
To obtain class information for generic types at runtime, consider other Stack Overflow-anointed solutions. Beware against inflating bytecode or intensive runtime introspection.
Was this article helpful?