0

I am wondering if it is possible to instantiate an object (companion object) dynamically using Manifest. I want to parse json in MongoRecord but to do so, I have to understand which is the type that is passed.

def getCompanion[T](implicit mf : Manifest[T])={
    if (mf <:< classOf[MongoRecord[C]]){
       Class[C].asInstanceOf[MongoRecord].setFieldsFromJSON(request.body.toString)
    }

}

but I am receiving an error during compilation:

error: object Class is not a value Class[C].asInstanceOf[MongoRecord].setFieldsFromJSON(request.body.toString)

it is a difficult topic to me. Perhaps it is not feasible but I would like to know if it is possible? Thanks

Malte Schwerhoff
  • 12,684
  • 4
  • 41
  • 71
Matroska
  • 6,885
  • 14
  • 63
  • 99
  • You cannot instantiate (companion) objects at all. Please clarify. – Malte Schwerhoff Jan 15 '13 at 10:37
  • I would like to call a method that is callable in this way MongoRecordCompanionObject.setFieldsFromJSON(jsonString). For sure I could do this using pattern matching on manifest erasure but I would like to know if I can call a companion dinamically knowing its name at runtime (without reflection). Is it possible? – Matroska Jan 15 '13 at 10:44
  • And how would you invoke `getCompanion`? Probably not as `getCompanion[MongoRecordCompanionObject]` - maybe `getCompanion` should take as an argument some instance of which you'd like to get the companion object? – Malte Schwerhoff Jan 15 '13 at 10:48
  • 1
    Have a look at http://stackoverflow.com/questions/9172775/get-companion-object-of-class-by-given-generic-type-scala and at http://stackoverflow.com/questions/11020746/get-companion-object-instance-with-new-scala-reflection-api – Malte Schwerhoff Jan 16 '13 at 08:31

0 Answers0