在Scala中运行时检查参数类型(来自可变长度参数列表)

时间:2013-02-24 22:36:10

标签: scala variadic-functions runtime-type

我正在为可以接受应用于给定数据结构的规则的系统设计接口。

主系统应该作为驱动程序接收命令,例如“将规则X应用于参数U,V,W,......”。我不知道编译时所有可能的规则,所以我想在规则定义中嵌入参数类型信息并对其进行验证。

现在规则定义如下:

trait Rule {
  val argTypes: Seq[Class[_]]
  def apply(stt: State, args: Seq[Any])
}

args中的实际参数数必须与argTypes中定义的类型数相匹配,方法apply应返回操作状态。 (实际上,这是简化的解释,但这是一般的想法)。

我还实现了一个名为checkTypes的函数来验证实际参数的类型是否与argTypes中定义的类型匹配。

def checkTypes(args: Seq[Any]) {
  if (argTypes.size != args.size) {
    val msg = "Number of arguments (%d) does not match expected number (%d)."
    throw new IllegalArgumentException(msg.format(args.size, argTypes.size))
  }
  val err = "Incompatible argument type for [%s]. Expected: %s. Found: %s."
  for (i <- 0 until argTypes.size) {
    val formalClass = argTypes(i)
    val arg = args(i)
    val actualClass = arg.asInstanceOf[AnyRef].getClass
    if (!(formalClass isAssignableFrom actualClass)) {
      val errMsg = err.format(arg, formalClass.getName, actualClass.getName)
      throw new IllegalArgumentException(errMsg)
    }
  }
}

问题在于,每当我尝试传递整数参数(从控制台或文本文件中读取)时,checkTypes过程都会失败并显示以下消息:java.lang.IllegalArgumentException: Incompatible argument type for [1]. Expected: int. Found: java.lang.Integer.

我正在使用Integer.parseInt(t).asInstanceOf[Int]转换整数参数,并且规则需要两个Int类型的参数

那么,有没有更有效的方法来检查运行时的参数类型?

OR

如何将String转换为Int for real?

提前致谢。


作为最低工作示例,这是Scala REPL中的一个会话,它会引发异常:

scala> val argTypes: Seq[Class[_]] = Seq(classOf[Int], classOf[Int])
argTypes: Seq[Class[_]] = List(int, int)

scala> def checkTypes(args: Seq[Any]) {
     |   if (argTypes.size != args.size) {
     |     val msg = "Number of arguments (%d) does not match expected number (%d)."
     |     throw new IllegalArgumentException(msg.format(args.size, argTypes.size))
     |   }
     |   val err = "Incompatible argument type for [%s]. Expected: %s. Found: %s."
     |   for (i <- 0 until argTypes.size) {
     |     val formalClass = argTypes(i)
     |     val arg = args(i)
     |     val actualClass = arg.asInstanceOf[AnyRef].getClass
     |     if (!(formalClass isAssignableFrom actualClass)) {
     |       val errMsg = err.format(arg, formalClass.getName, actualClass.getName)
     |       throw new IllegalArgumentException(errMsg)
     |     }
     |   }
     | }
checkTypes: (args: Seq[Any])Unit

scala> val args: Seq[Any] = Seq("1".toInt, "2".toInt)
args: Seq[Any] = List(1, 2)

scala> checkTypes(args)
java.lang.IllegalArgumentException: Incompatible argument type for [1]. Expected: int. Found: java.lang.Integer.
    at $anonfun$checkTypes$1.apply$mcVI$sp(<console>:20)
    at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:78)
    at .checkTypes(<console>:14)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
    at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
    at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
    at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
    at java.lang.Thread.run(Thread.java:679)

1 个答案:

答案 0 :(得分:2)

您在盒装类型(java.lang.Integer)和未装箱类型(scala.Int == java int)之间存在不匹配。实际的实例是盒装的,但是你要根据原始的classOf进行测试。

以下是基元被装箱时会发生什么的一个例子:

scala> 5.getClass
res0: Class[Int] = int

scala> (5: Any)
res1: Any = 5

scala> res1.getClass
res2: Class[_] = class java.lang.Integer

请注意,如果您在Any上进行模式匹配并获得基元,它实际上会选择装箱的副本并为您取消装箱。

scala> res1 match { case i: Int => println(i); case _ => }
5

由于您知道必须被装箱,因此根据您编写的代码,您也可以只检查Integer而不是Int(即使用{{ 1}})。