isInstanceOf/asInstanceOf
scala中对象提供isInstanceOf和asInstanceOf方法。
- isInstanceOf判断对象是否为指定类以及其子类的对象
- asInstanceOf将对象转换为指定类型
用法
// 判断对象是否为指定类型
val trueOrFalse:Boolean = 对象.isInstanceOf[类型]
// 将对象转换为指定类型
val 变量 = 对象.asInstanceOf[类型]
代码示例
object Test01 {
class Person
class Student extends Person
def main(args: Array[String]): Unit = {
val student:Student = new Student
// 判断 student 是否 为 Person 类型 或着是 Person 的子类
if (student.isInstanceOf[Person]) {
//将 student 转化为 student 类型
val person = student.asInstanceOf[Person]
val bool = person.isInstanceOf[Person]
println(s"person = ${bool}")
}
}
}
getClass和classOf
isInstanceOf 只能判断对象是否为指定类以及其子类的对象,而不能精确的判断出,对象就是指定类的对象。如果要求精确地判断出对象就是指定类的对象,那么就只能使用 getClass 和 classOf 。
用法
- p.getClass可以精确获取对象的类型
- classOf[x]可以精确获取类型
- 使用==操作符可以直接比较类型
代码示例
object Test02 {
//定义一个Person 类
class Person
//定义一个Student 类继承 Person 类
class Student extends Person
def main(args: Array[String]): Unit = {
//创建一个 Person 类的对象
val p = new Person
//使用 isInstanceOf判断p 是否为 Person 类的实例
val bool = p.isInstanceOf[Person]
println(s"bool = ${bool}") //true
//判断p 的 类型 是否为Person 类
val bool1 = p.getClass == classOf[Person]
println(s"bool1 = ${bool1}") //false
//判断 p 的类型是否为student 类
val bool2 = p.getClass == classOf[Student]
println(s"bool2 = ${bool2}")
}
}