Write a Java program to check anonymous class using isAnonymousClass() method


The main() method creates a new anonymous class using the syntax new Object() {}, which creates a new object of the Object class without explicitly defining a class name. The getClass() method is then called on the new object to obtain its Class object.

The isAnonymousClass() method is then called on the Class object, which returns true if the class is an anonymous class, and false otherwise.

Finally, the program prints a message to the console indicating whether the class is anonymous or not, based on the value returned by isAnonymousClass().

This is because the new Object() {} syntax creates an instance of an anonymous class that extends Object, which is confirmed by the call to isAnonymousClass().

Source Code

public class Check_Anonymous
{
	public static void main(String[] args)
	{
		Class < ? extends Object > cls = new Object() {}.getClass();
		boolean res = cls.isAnonymousClass();
 
		if (res)
		{
			System.out.println("It is an Anonymous Class");
		}
		else
		{
			System.out.println("It is Not an Anonymous Class");
		}
	}
}

Output

It is an Anonymous Class