Scala, sugar in Java : make a type parametrized factory
The basic code to create an instance from a Type parameter :
(full source on github )
// Scala
def newOne[T]()(implicit m: Manifest[T]): T = {
// assume T as a no-args constructor
m.erasure.newInstance().asInstanceOf[T]
}
// sample call
val v = newOne[String]()
// Java
public <T> T newOne(Class<T> clazz) {
return clazz.newInstance();
}
// sample call from java
String v = newOne(String.class);
// sample call from scala
val v = newOne(classOf[String])