在Java中,instanceof
和typeof
是兩個不同的操作符。
instanceof
操作符:
instanceof
用于判斷一個對象是否屬于某個特定類型或其子類型。
語法格式為:object instanceof type
,其中object
是要判斷的對象,type
是要判斷的類型。
返回一個布爾值,如果對象是指定類型或該類型的子類實例,則返回true
,否則返回false
。
instanceof
主要用于運行時類型判斷,可以在程序中根據對象的實際類型執行相應的操作。
示例代碼:
class Animal {}
class Dog extends Animal {}
pubpc class Main {
pubpc static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Animal) {
System.out.println("animal是Animal類型");
}
if (animal instanceof Dog) {
System.out.println("animal是Dog類型");
}
}
}
2、typeof
操作符:
在Java中,并沒有像typeof
這樣的操作符。
typeof
在其他編程語言(如JavaScript)中存在,用于獲取操作數的數據類型。
在Java中,我們可以使用getClass()
方法來獲取對象的運行時類型,或者使用getSimpleName()
方法獲取類的簡單名稱。
示例代碼:
pubpc class Main {
pubpc static void main(String[] args) {
String str = "Hello";
Class> strClass = str.getClass();
System.out.println(strClass.getSimpleName()); // 輸出:String
}
}
綜上所述,instanceof
操作符用于判斷對象的類型,而typeof
在Java中不存在,我們可以使用getClass()
方法來獲取對象的運行時類型。