Explain Codes LogoExplain Codes Logo

How to call getClass() from a static method in Java?

java
class-literals
java-8
best-practices
Anton ShumikhinbyAnton Shumikhin·Dec 7, 2024
TLDR

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:

public static void getClassEquivalent() { System.out.println(MyClass.class.getName()); // Output: MyClass's fabulous name }

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.

LogFactory.getLog(MyClass.class.getName()); // Auto-pilot mode enabled

No getClass()? No problem

In a static method, getClass() won't help to access resources. But MyClass.class.getResource() and Thread.currentThread().getContextClassLoader() will.

URL resource = MyClass.class.getResource("FileName.xyz"); // Accessing resources? Easy peasy.

Beware the anonymous subclass

Desperate times call for desperate measures, like the anonymous subclass trick. But remember, with great power...

Class<?> clazz = new Object(){}.getClass().getEnclosingClass(); // I am... wait, who am I?

...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.

// Here be dragons! Proceed with caution.