The scala getClass and classOf

getClass和classOf
IsInstanceOf determines whether only the specified target object class and its subclasses, and can not accurately judged, is the object that the specified class. If fine is determined that the target object for the specified class, and then only use getClass classOf.
Usage
p.getClass type of the object can be accurately acquired
classOf [x] can accurately obtain the type of
use == operator type can be compared directly
exemplary
example shows
the definition of a Person class
defines a Student Person class inherits from class
to create a Student class object and specify it is of type Person type
tests using isInstance determines whether the object is a Person type
tests using getClass / classOf determines whether the object type Person is
tested using getClass / classOf Student determines whether the object type is a
reference code

class Person4
class Student4 extends Person4

object Student4{
  def main(args: Array[String]) {
    val p:Person4=new Student4
    //判断p是否为Person4类的实例
    println(p.isInstanceOf[Person4])//true
 //判断p的类型是否为Person4类
    println(p.getClass == classOf[Person4])//false
 //判断p的类型是否为Student4类
    println(p.getClass == classOf[Student4])//true
  }
}

Here Insert Picture Description
answer:
Here Insert Picture Description

Published 139 original articles · won praise 333 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_45765882/article/details/104302931