2

I have a class name string representation

val cls = Class.forName("clsName")
def fromJson[T: Manifest](me: String): T = {
Extraction.extract[T](net.liftweb.json.parse(me))
}

I would like to use it as T:manifest i.e

JsonConverter.fromJson[cls.type](stringData)

this returns an error

tried also

val t = Manifest.classType(cls)
JsonConverter.fromJson[t](stringData) // compile error 

what is the best way to it ? is there a way to avoid using reflection ?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
igx
  • 4,101
  • 11
  • 43
  • 88

1 Answers1

6

You could try something like this:

val cls = Class.forName(myClassName)
val m = Manifest.classType(cls)
val myObj:Any = JsonConverter.fromJson(stringData)(m) 

One nuance to this approach is that you have to explicitly type the object as an Any. This is because you don't have the class as compile time and the call to classType is not supplied its type param so the Manifest returned is Manifest[Nothing]. Not ideal, but it works.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95