Scala:为什么 java.lang.IllegalArgumentException:无法将给定对象格式化为日期?

Scala: Why java.lang.IllegalArgumentException: Cannot format given Object as a Date?

我有以下导致我无法解释的 RuntimeException 错误的简单代码:

import java.text.MessageFormat
import java.util.Date
import org.apache.commons.cli._
import org.joda.time._
import org.joda.time.format.DateTimeFormat

object TestMain {
  def doFormat(value: Any): String = {
    val ClassOfDouble = classOf[Double]
    val ClassOfDate = classOf[Date]
    val ClassOfDateTime = classOf[DateTime]
    val result: String = value.getClass match {
      case ClassOfDouble => MessageFormat.format("{0,number,#.####################}", Array(value.asInstanceOf[DateTime]))
      case ClassOfDate => MessageFormat.format("{0,date,yyyy.MM.dd}", Array(value.asInstanceOf[Date]))
      case ClassOfDateTime => DateTimeFormat.forPattern("yyyy.MM.dd HH:mm:SSS").print(value.asInstanceOf[DateTime])
      case _ => value.toString
    }
    result
  }

  def main(args: Array[String]): Unit = {
    println(doFormat(new Date()))
  }
}  

... 以及由此产生的运行时错误:

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at java.text.MessageFormat.subformat(Unknown Source)
    at java.text.MessageFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at java.text.MessageFormat.format(Unknown Source)
    at test.TestMain$.doFormat(TestMain.scala:28)
    at test.TestMain$.main(TestMain.scala:39)
    at test.TestMain.main(TestMain.scala)

发生这种情况是因为您将 Array 传递给 format 方法。您可以直接使用 Date

case ClassOfDate => MessageFormat.format("{0,date,yyyy.MM.dd}", value.asInstanceOf[Date])

有了这个,输出将是:

2017.10.17

您不需要用数组包装 MessageFormat.format() 的第二个参数,因为它需要可变参数。

使用数组调用令人困惑。不清楚 Array 是可变参数(对象...)还是可变参数(对象)的第一个参数。它使用第二个,您遇到异常。