Netherwire
Netherwire

Reputation: 2787

How to determine whether java class is anonymous?

I have such code:

package x.y.z;

public class Test
{
    private static class MyRunnable implements Runnable
    {
        @Override
        public void run()
        {
            System.out.println("World");
        }
    }

    public static void main(String[] args)
    {
        final Runnable r1 = new Runnable() {
            @Override
            public void run()
            {
                System.out.println("Hello");
            }
        };

        final Runnable r2 = new MyRunnable();

        r1.run();
        r2.run();
    }
}

I am working on some code analysis module, and I want to prove that r1 is an anonymous class instance and r2 is not. Both of them are valid objects having the same base class or an interface. How can I do this?

Refinement: All classes are being loaded, so I do not need to analyze the text.

Upvotes: 0

Views: 539

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075019

There's the isAnonymousClass method on Class, so:

if (r1.getClass().isAnonymousClass()) {
    // ...

Upvotes: 6

Related Questions