【发布时间】:2018-05-15 03:29:55
【问题描述】:
我想构建一个简单的库,开发人员可以在其中定义一个表示命令行参数的 Scala 类(为了简单起见,只有一组必需的参数——没有标志或可选参数)。我希望该库能够解析命令行参数并返回该类的一个实例。图书馆的用户会做这样的事情:
case class FooArgs(fluxType: String, capacitorCount: Int)
def main(args: Array[String]) {
val argsObject: FooArgs = ArgParser.parse(args).as[FooArgs]
// do real stuff
}
如果提供的参数与预期类型不匹配(例如,如果有人在预期 Int 的位置传递字符串“bar”),解析器应该抛出运行时错误。
如何在事先不知道其形状的情况下动态构建FooArgs?由于FooArgs 可以有任何数量或类型,我不知道如何迭代命令行参数,将它们转换或转换为预期的类型,然后使用结果构造FooArgs。基本上,我想按照这些思路做一些事情:
// ** notional code - does not compile **
def parse[T](args: Seq[String], klass: Class[T]): T = {
val expectedTypes = klass.getDeclaredFields.map(_.getGenericType)
val typedArgs = args.zip(expectedTypes).map({
case (arg, String) => arg
case (arg, Int) => arg.toInt
case (arg, unknownType) =>
throw new RuntimeException(s"Unsupported type $unknownType")
})
(klass.getConstructor(typedArgs).newInstance _).tupled(typedArgs)
}
关于如何实现这样的目标有什么建议吗?
【问题讨论】: