Scala从字符串表示中获取类类型

编程入门 行业动态 更新时间:2024-10-21 16:07:35
本文介绍了Scala从字符串表示中获取类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类名字符串表示

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)) }

我想将其用作 T:manifest 即

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

JsonConverter.fromJson[cls.type](stringData)

返回错误

也试过

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 ?

推荐答案

你可以试试这样的:

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

此方法的一个细微差别是您必须将对象显式键入为 Any.这是因为您没有将类作为编译时,并且对 classType 的调用未提供其类型参数,因此返回的 Manifest 是 Manifest[Nothing].不理想,但有效.

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.

更多推荐

Scala从字符串表示中获取类类型

本文发布于:2023-11-08 13:50:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   类型   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!