2010-06-29 7 views
3

메시지를 감싸고 랩핑 한 메시지를 기록하고 싶습니다. 나는 더 나은 솔루션이 있는지 궁금클래스를 가져 오는 방법 _ : 모두

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

: 내가 찾을 수

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

유일한 해결책은 모든 것을 일치한다? 다음이 방법은 :(

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는 더 이상 어떤 contorsion을 할 필요가 없습니다, Any (뿐 아니라 AnyRef에) 볼 수 있습니다 그냥 할 수있는 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] 하나를 반환
관련 문제