本文翻译自:Use of “instanceof” in Java [duplicate]
What is the 'instanceof' operator used for? 什么是'instanceof'运算符用于?
I learned that Java has the instanceof
operator. 我了解到Java有instanceof
运算符。 Can you elaborate where it is used and what are its advantages? 你能详细说明它的使用地点和优势吗?
#1楼
参考:https://stackoom.com/question/vA4h/在Java中使用-instanceof-重复
#2楼
instanceof is a keyword that can be used to test if an object is of a specified type. instanceof是一个关键字,可用于测试对象是否为指定类型。
Example : 示例:
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
#3楼
instanceof
is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. instanceof
用于检查对象是否是类的实例,子类的实例或实现特定接口的类的实例。
Read more from the Oracle language definition here. 在此处阅读Oracle语言定义中的更多内容。
#4楼
Basically, you check if an object is an instance of a specific class. 基本上,您检查对象是否是特定类的实例。 You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete). 当你有一个超类或接口类型的对象的引用或参数并且需要知道实际对象是否具有其他类型(通常更具体)时,通常使用它。
Example: 例:
public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}
Note that if you have to use that operator very often it is generally a hint that your design has some flaws. 请注意,如果您经常使用该运算符,通常会暗示您的设计存在一些缺陷。 So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule). 因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该一般规则也有例外)。
#5楼
instanceof
can be used to determine the actual type of an object: instanceof
可用于确定对象的实际类型:
class A { }
class C extends A { }
class D extends A { }
public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}