igx
igx

Reputation: 4231

Scala Getting class type from string representation

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 ?

Upvotes: 2

Views: 3430

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

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.

Upvotes: 6

Related Questions