Anonymous Types and Java 10 var

By Adrian Smith12 Mar 2019400 words2 mins to read

There is a nice new feature introduced by type-inference in Java. I've wanted this feature for a while, but without type-inference, it wasn't possible.

The feature is the ability to create a local variable of an anonymous class, and then use the particularities of that anonymous class.

For example, in Java 9, to access a new method you'd defined on an anonymous class, you'd need to create a named class. That's because the type of variables needed to be specified in the source code, and an anonymous class doesn't have a name.

class Foo extends MyThing {
    // new method, not overridden
    int foo() { return 42; }
}
Foo x = new Foo();
System.out.println(x.foo());

Now in Java 10, you can access the methods you've defined directly on the object

var x = new MyThing() {
    // new method, not overridden
    int foo() { return 42; }
};
System.out.println(x.foo());

You might argue that is a bit of a weird feature. I'll admit my examples above are not particularly persuasive as to why you might want to do this.

Nevertheless, it's a feature I've always wanted, especially hacking things into weird Java APIs (e.g. passing an object to a Java API that provides things both to my code and the the code I'm calling, for example overriding methods provided by the Java API to keep a count of something, and then allowing my calling code to access that count.)

I have long been a fan of type-inference. Until Java 10 I used Lombok's "val" type-inference feature. Lombok re-wrote the source code at compile time to insert the correct type in place of its "val" type. As an anonymous type cannot be named in source code, neither can Lombok insert its name into the source code. So the above doesn't work with Lombok's "val". (Believe me I tried!)

BTW My current project was written entirely using Lombok's "val" type inference, and I've now converted it 100% to use Java 10's "var". It works well I have to say, and as an additional benefit compile times are about half of what they used to be with Lombok's "val".

This article was written by Adrian Smith on 12 Mar 2019

Follow me: Facebook | Twitter | LinkedIn | Email

More on: Java