Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

How to check if a class is an anonymous class in Java

Ravi

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();
    }
}
isAnonymousClass() method

Explanation

  • Lines 3–5: We define a static method named example1() where we check if the Main class is anonymous or not using the isAnonymousClass() method.
  • Lines 7–10: We provide a static function named example2() that uses the isAnonymousClass() method to determine whether the runtime class of the Object class is an anonymous class or not.
  • Lines 14–15: We call the example1() and example2() methods.

RELATED TAGS

java
RELATED COURSES

View all Courses

Keep Exploring