在编写Java/Scala脚本时,经常需要对数据类型进行判断或者转换。特将相关使用方法整理出来,方便以后查阅。
一、Java
1、检查某个对象是否属于某个给定的类:obj instanceof Class
class User {
Long id;
}
class Person extends User {
String name;
}
public static void main(String[] args) {
Object s1 = new User();
Object s2 = new Person();
System.out.println(s1 instanceof User);
System.out.println(s1 instanceof Person);
System.out.println(s2 instanceof User);
System.out.println(s2 instanceof Person);
}
运行结果:
true
false
true
true
2、类型转换:Class (obj)
Object str = "test";
String s = (String) str;
3、检查某个对象是否指向某个给定的类,不包括其子类:
class User {
Long id;
}
class Person extends User {
String name;
}
public static void main(String[] args) {
Object s1 = new User();
Object s2 = new Person();
System.out.println(s1.getClass() == Person.class);
System.out.println(s2.getClass() == Person.class);
}
运行结果:
false
true
二、Scala
1、检查某个对象是否属于某个给定的类:obj.isInstanceOf[Class]
object ScalaT1 {
def main(args: Array[String]): Unit = {
val s1 = new School()
val s2 = new House()
println(s1.isInstanceOf[School])
println(s1.isInstanceOf[House])
println(s2.isInstanceOf[School])
println(s2.isInstanceOf[House])
}
}
class School {}
class House extends School {}
运行结果:
true
false
true
true
2、类型转换:obj.asInstanceOf[Class]
object ScalaT1 {
def main(args: Array[String]): Unit = {
val s1 = new School()
val s2 = new House()
println(s1.asInstanceOf[School])
println(s1.asInstanceOf[House]) // error: School cannot be cast to House
println(s2.asInstanceOf[School])
println(s2.asInstanceOf[House])
}
}
class School {}
class House extends School {}
3、检查某个对象是否指向某个给定的类,不包括其子类:
object ScalaT1 {
def main(args: Array[String]): Unit = {
val s1 = new School()
val s2 = new House()
println(s1.getClass == classOf[School])
println(s1.getClass == classOf[House])
println(s2.getClass == classOf[School])
println(s2.getClass == classOf[House])
}
}
class School {}
class House extends School {}
运行结果:
true
false
false
true