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 ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.