如何检查对象以查看其类型并返回Casted对象 [英] How Can I Check an Object to See its Type and Return A Casted Object

查看:134
本文介绍了如何检查对象以查看其类型并返回Casted对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,我通过一个对象。在这种方法,我检查它的类型,并根据类型我做的东西,并返回一个长。我试过了每一种方式,我可以想到这样做,我总是得到几个编译器错误告诉我它期望一个特定的对象,但另一个。有人可以向我解释我做错了,指导我在正确的方向?我到目前为止的尝试如下:

I have method to which I pass an object. In this method I check it's type and depending on the type I do something with it and return a Long. I have tried every which way I can think of to do this and I always get several compiler errors telling me it expects a certain object but gets another. Can someone please explain to me what I am doing wrong and guide me in the right direction? What I have tried thus far is below:

  override def getInteger(obj:Object) = {
    if (obj.isInstanceOf[Object]) null
    else if (obj.isInstanceOf[Number]) 
      (obj:Number).longValue()
    else if (obj.isInstanceOf[Boolean]) 
      if (obj:Boolean) 1 else 0
    else if (obj.isInstanceOf[String]) 
      if ((obj:String).length == 0 | (obj:String) == "null") 
        null
      else
          try {
            Long.parse(obj:String)
          } catch {
            case e: Exception => throw new ValueConverterException("value \"" + obj.toString() + "\" of type " + obj.getClass().getName() + " is not convertible to Long")        
          }
  }


推荐答案

模式匹配会让它更好。

Pattern matching would make it much more nicer.

def getInteger(obj: Any) = obj match {
  case n: Number => n.longValue
  case b: Boolean => if(b) 1 else 0
  case s: String if s.length != 0 && s != "null" => s.toLong
  case _ => null
}

这篇关于如何检查对象以查看其类型并返回Casted对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆