ses
ses

Reputation: 13362

java syntax like Object(){}

Class clazz = new Object(){}.getClass();

Why is this possible and what would it mean? Could someone please remind me?

For example:

public class Testing {
    public static void main(String[] args) {
        Class clazz = new Object(){}.getClass();
        System.out.println(clazz);
    }
}

The result is: class Testing$1

Upvotes: 2

Views: 110

Answers (3)

josefx
josefx

Reputation: 15656

Its the same as the following code:

public class Testing{
      private class Anon extends Object{
      }
      public static void main(String[] args) {
          Class clazz = new Anon().getClass();
          System.out.println(clazz);
      }
}

The Testing$1 is the name of the class, it being the first anonymous class defined in the class Testing.

These anonymous classes can be used to implement interfaces in the place where you use it and they have access to local final variables.

final String text = "Written by new Thread";
Thread thread = new Thread(new Runnable(){
     public void run(){
         System.out.println(text);
}});
thread.start();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502526

It creates an anonymous inner class subclassing Object. The main use I've seen with an empty body is in Guice, for TypeLiteral, where it's used to capture generic type arguments:

key = new TypeLiteral<List<String>>() {};

This is useful because type erasure doesn't apply to the superclass here, so Guice is able to get the List<String> part out, which can't be expressed as a normal class literal.

Upvotes: 4

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116286

new Object(){} creates an anonymous inner class, as a subclass of Object. It is an inner class of Testing, thus it gets a compiler generated name like the one you saw.

Upvotes: 9

Related Questions