mardi 22 septembre 2015

Retrieving original class types from anonymous classes

Given a class with an empty constructor and a var:

class MyClass() {
  var myVar: Int = 0
}

When the class is instantiated with a closure, this yields an object with the underlying type of an anonymous class rather than MyClass:

// getClass yields type my.package.MainClass$$anonfun$1$anonfun$apply...
val myNewClassInstance: MyClass = new MyClass() { myVar = 2}

Is it possible to retrieve the original class type MyClass using reflection and the object myNewClassInstance, in order to create new object instances from it?





Aucun commentaire:

Enregistrer un commentaire