One
The instanceof operator is used to indicate at run time whether an object is an instance of a particular class. Instanceof, by returning a Boolean value, indicates whether the object is a particular class or an instance of its subclass. Usage:
Result = Object Instanceof class
Parameters: Result required option. Any variable. The object must be selected. An arbitrary object expression. Class must be selected. Any defined object class.
Note: If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.
For example:
Boolean b;
String str = "Foo";
b = (str instanceof String); True
b = (str instanceof Object); Also true
b = (str instanceof Date); False, not a Date or subclass
Attention:
1) The null value is not an instance of any object, so the following example returns FALSE, regardless of what type the variable declares.
String s = null;
if (S instanceof String)
False, won ' t happen
2 instanceof can also correctly report whether an object is an array and a specific interface type.
if (foo instanceof byte[])
Two
It is generally possible that when we use Java Rtti technology, we use instanceof to determine whether an object belongs to a class, but sometimes the class inherits from a parent class, so it is not strictly determined whether it is your own class, not your own parent class. This time to use another way of thinking is also a good--getclass judgment, of course there are other ways to judge, but their own summary. If there are any good other ways please enlighten me.
public class Test {
public static void Main (String arg[]) {
ClassA a = new ClassA ();
CLASSB B = new ClassB ();
CLASSC C = new CLASSC ();
Sayclass (a);
Sayclass (b);
Sayclass (c);
System.out.println ("---------------------------------");
Equalclass (a);
Equalclass (b);
Equalclass (c);
}
public static void Sayclass (Object o) {
if (o instanceof ClassA) {
System.out.println ("ClassA");
}else if (o instanceof classb) {
System.out.println ("ClassB");
}
}
public static void Equalclass (Object o) {
if (O.getclass (). Equals (ClassA.class)) {
System.out.println (O.getclass (). GetName ());
}else if (O.getclass (). Equals (Classb.class)) {
System.out.println (O.getclass (). GetName ());
}else if (O.getclass (). Equals (Classc.class)) {
System.out.println (O.getclass (). GetName ());
}
}
}
Class classa{
ClassA () {};
}
Class classb{
ClassB () {};
}
Class CLASSC extends classa{
CLASSC () {};
}
Article reproduced from: http://blog.sina.com.cn/s/blog_4e345ce70100x7xp.html
http://blog.csdn.net/yuri99/article/details/8504256