How to check if a class is an anonymous class in Java
Overview
In Java, a nested class without a name is called an anonymous class.
A nested class is one that is enclosed within another class. Because anonymous classes are embedded within other classes, they are also known as anonymous inner classes.
The isAnonymousClass() method
The isAnonymousClass() method in Java checks whether a class is an anonymous class or not.
Syntax
public boolean isAnonymousClass()
Parameters
This method doesn’t take any parameters.
Return value
This method returns a boolean value. If the class is anonymous, it returns true. Otherwise, it returns false.
Example
public class Main{public static void example1(){System.out.println(Main.class + " is anonymous - " + Main.class.isAnonymousClass());}public static void example2(){Class<?> runtimeClass = new Object() {}.getClass();System.out.println(runtimeClass + " is anonymous - " + runtimeClass.isAnonymousClass());}public static void main(String[] args) {example1();example2();}}
Explanation
- Lines 3–5: We define a static method named
example1()where we check if theMainclass is anonymous or not using theisAnonymousClass()method. - Lines 7–10: We provide a static function named
example2()that uses theisAnonymousClass()method to determine whether the runtime class of theObjectclass is an anonymous class or not. - Lines 14–15: We call the
example1()andexample2()methods.