instanceof 關鍵字用於判斷某個實例是不是某個類的實例化對象,形如:ui
String.class instanceof Class "test" instanceof String
isInstance是Class類中的方法,也是用於判斷某個實例是不是某個類的實例化對象,可是指向則相反。this
但這樣就帶來一個疑問,爲何咱們須要這個方法呢,官方文檔如此解釋:spa
Determines if the specified Object is assignment-compatible with the object represented by this Class.
This method is the dynamic equivalent of the Java language instanceof operator.
The method returns true if the specified Object argument is non-null
and can be cast to the reference type represented by this Class object without raising a ClassCastException.
It returns false otherwise.
加粗的部分就是主要的區別,主要突出一點:
動態等效(dynamic equivalent)
可是這樣並不容易理解,動態等效,雖然字面意思是運行時等效,一個例子會方便理解一些。
有了這點特性,咱們能夠在運行時判斷兩個類是否能夠相互強轉。code
3、示例用法對象
public static void main(String[] args) { System.out.println("\"test\" instance of String:"+("test" instanceof String)); System.out.println("\"test\" instance of Object:"+("test" instanceof Object)); System.out.println("\"test\".getClass().isInstance(Object.class):"+("test".getClass().isInstance(Object.class))); System.out.println("\"test\".getClass().isInstance(String.class):"+("test".getClass().isInstance(String.class))); System.out.println("String.class.isInstance(Object.class):"+(String.class.isInstance(Object.class))); System.out.println("String.class.isInstance(String.class):"+(String.class.isInstance(String.class))); System.out.println("String.class.isInstance(\"test\"):"+(String.class.isInstance("test"))); System.out.println("Object.class.isInstance(\"test\"):"+(Object.class.isInstance("test"))); Object object="ok"; System.out.println("Double.class.isInstance(\"test\"):"+(Double.class.isInstance("test"))); Set<?> a=new HashSet<String>(); Set<String> b=new HashSet<String>(); System.out.println("a is b:"+aIsB(a,b)); } static boolean aIsB(Object a,Object b){ return a.getClass().isInstance(b); }
輸出:blog
"test" instance of String:true
"test" instance of Object:true
"test".getClass().isInstance(Object.class):false
"test".getClass().isInstance(String.class):false
String.class.isInstance(Object.class):false
String.class.isInstance(String.class):false
String.class.isInstance("test"):true
Object.class.isInstance("test"):true
Double.class.isInstance("test"):false
a is b:trueci