Java/Scala 类型检查与转换的使用

在编写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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

magic_kid_2010

你的支持将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值