The specific differences between instanceof and Isinstance in Java
In the think in Java generics Chapter encountered this problem, some blog vague mentions that isinstance is the dynamic implementation of instanceof, consult the document reference SOF some of the answers are as follows:
An object that represents whether the object obj is the class class or its subclasses
- An object is an object of its own class
- An object is an object of its own class parent class and interface
- All objects are objects of the object class
- All null-related is False
This is described in the documentation
Determines if the specified object is a assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.
That is, whether the object obj can be converted to a class object, which is dynamically equivalent to instanceof
- An object that can be transformed into an object of its own class
- An object that can be converted to the parent class of its own class and an object that implements the interface
- All objects can be converted to objects of the object class
- All null-related is False
Visible is the same as instanceof usage, the key is dynamic equivalence
classfather{}classSonextendsfather{} Public classtest{ Public Static Boolean dynamicequal(Object fatherobj,object sonobj) {returnFatherobj.GetClass().isinstance(Sonobj);//Pass //return sonobj instanceof Father;//Pass //Return sonobj instanceof (Fatherobj.getclass ());//error} Public Static void Main(string[] args) {//same usingFather Father =New Father(); Son son =New Son(); System. out.println(soninstanceofSon);//TrueSystem. out.println(soninstanceofFather);//TrueSystem. out.println(soninstanceofObject);//TrueSystem. out.println(NULL instanceofObject);//FalseSystem. out.println(); System. out.println(Son.class.isinstance(son));//TrueSystem. out.println(Father.class.isinstance(son));//TrueSystem. out.println(Object.class.isinstance(son));//TrueSystem. out.println(Object.class.isinstance(NULL));//FalseSystem. out.println();//different usingSystem. out.println(dynamicequal(father, son)); }}
For obj.instanceof (Class), the compiler needs to know the concrete type of the class at compile time
For Class.isinstance (obj), the compiler does type checking at run time, so it can be used for reflection, in generics
Reference:
Https://stackoverflow.com/questions/8692214/when-to-use-class-isinstance-when-to-use-instanceof-operator
Https://stackoverflow.com/questions/15757014/isinstance-instanceof-why-theres-no-generic-way
http://blog.csdn.net/u010002184/article/details/79306195
The specific differences between instanceof and Isinstance in Java