2010-06-29 41 views
3

我包裝了一條消息並希望記錄我已包裝的消息。如何獲得_的類:任何

val any :Any = msg.wrappedMsg 
var result :Class[_] = null 

我能找到的唯一的解決辦法是匹配的一切:

result = any match { 
    case x:AnyRef => x.getClass 
    case _:Double => classOf[Double] 
    case _:Float => classOf[Float] 
    case _:Long => classOf[Long] 
    case _:Int => classOf[Int] 
    case _:Short => classOf[Short] 
    case _:Byte => classOf[Byte] 
    case _:Unit => classOf[Unit] 
    case _:Boolean=> classOf[Boolean] 
    case _:Char => classOf[Char] 
} 

我不知道是否有更好的解決辦法? 以下2種方法不工作:(

result = any.getClass //error 
// type mismatch; found : Any required: ?{val getClass: ?} 
// Note: Any is not implicitly converted to AnyRef. 
// You can safely pattern match x: AnyRef or cast x.asInstanceOf[AnyRef] to do so. 
result = any match { 
    case x:AnyRef => x.getClass 
    case x:AnyVal => /*voodoo to get class*/ null // error 
} 
//type AnyVal cannot be used in a type pattern or isInstanceOf 

回答

7

你可以安全地調用.asInstanceOf[AnyRef]任何斯卡拉值,這將盒子原語:

scala> val as = Seq("a", 1, 1.5,(), false) 
as: Seq[Any] = List(, 1, 1.5,(), false) 

scala> as map (_.asInstanceOf[AnyRef]) 
res4: Seq[AnyRef] = List(a, 1, 1.5,(), false) 

從那裏,你可以調用getClass

scala> as map (_.asInstanceOf[AnyRef].getClass) 
res5: Seq[java.lang.Class[_]] = List(class java.lang.String, class java.lang.Int 
eger, class java.lang.Double, class scala.runtime.BoxedUnit, class java.lang.Boo 
lean) 

測試2.8.0.RC6,我不知道它在2.7.7工作。

2.8中的絕對新值是從AnyVal派生的類的伴隨對象。它們含有得心應手boxunbox方法:

scala> Int.box(1) 
res6: java.lang.Integer = 1 

scala> Int.unbox(res6) 
res7: Int = 1 
3

不會鑄造只是做的伎倆,如錯誤信息提示?


scala> val d:Double = 0.0 
d: Double = 0.0 

scala> d.asInstanceOf[AnyRef].getClass 
res0: java.lang.Class[_] = class java.lang.Double 
3

隨着階2.10.0的,getClass可以用Any(而不僅僅是AnyRef),所以你不需要做任何contorsion了,並可以做any.getClass

請注意,您仍然必須準備好處理原始類型與其盒裝版本之間的雙重關係。

scala> 123.getClass 
res1: Class[Int] = int 

scala> val x : Int = 123 
x: Int = 123 

scala> x.getClass 
res2: Class[Int] = int 

scala> val x: AnyVal = 123 
x: AnyVal = 123 

scala> x.getClass 
res3: Class[_] = class java.lang.Integer 

scala> val x: Any = 123 
x: Any = 123 

scala> x.getClass 
res4: Class[_] = class java.lang.Integer 
: 舉例 getClass上的整數值將根據靜態類型的值的返回任一 java.lang.Integer.TYPE(類原始 Int類型)或 classOf[java.lang.Integer]