Saturday 14 January 2017

Java9: Diamond operator for anonymous classes

Java9 allow diamond with anonymous classes if the argument type of the inferred type is denotable. Prior to Java9, we need to specify the type argument to anonymous class.

public class ContainerFactory {

 <T> Container<T> createBox(T content) {
  
  // Prior to Java9, we have to put the 'T' here :(
  return new Container<T>(content) {
  };
 }

 public class Container<T> {
  private Container(T content) {

  }
 }
}

From java9 onwards, we no need to keep the type argument inside <>, Java automatically infer the types to anonymous class.

 <T> Container<T> createBox(T content) {
  
  // From java9, we no need to specify the type argument :)
  return new Container<>(content) {
  };
 }


public class ContainerFactory {

 <T> Container<T> createBox(T content) {
  
  // From java9, we no need to specify the type argument :)
  return new Container<>(content) {
  };
 }

 public class Container<T> {
  private Container(T content) {

  }
 }
}


Above application compiles on Java9. But when you try to compile above application on Java8, you will end up in following error.

$javac ContainerFactory.java
ContainerFactory.java:6: error: cannot infer type arguments for ContainerFactory.Container<T>
                return new Container<>(content) {
                                    ^
  reason: cannot use '<>' with anonymous inner classes
  where T is a type-variable:
    T extends Object declared in class ContainerFactory.Container
1 error



Previous                                                 Next                                                 Home

No comments:

Post a Comment