首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中'instanceof‘运算符是用来做什么的?

在Java中'instanceof‘运算符是用来做什么的?
EN

Stack Overflow用户
提问于 2011-09-06 07:28:14
回答 10查看 246.4K关注 0票数 168

instanceof操作符是用来做什么的?我见过像这样的东西

代码语言:javascript
复制
if (source instanceof Button) {
    //...
} else {
    //...
}

但这一切对我来说都没什么意义。我已经做了研究,但只提出了一些例子,没有任何解释。

EN

回答 10

Stack Overflow用户

发布于 2014-05-08 22:55:37

此运算符允许您确定对象的类型。它返回一个boolean值。

例如

代码语言:javascript
复制
package test;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class instanceoftest
{
    public static void main(String args[])
    {
        Map m=new HashMap();
        System.out.println("Returns a boolean value "+(m instanceof Map));
        System.out.println("Returns a boolean value "+(m instanceof HashMap));
        System.out.println("Returns a boolean value "+(m instanceof Object));
        System.out.println("Returns a boolean value "+(m instanceof Date));
    }
} 

输出为:

代码语言:javascript
复制
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
票数 15
EN

Stack Overflow用户

发布于 2011-09-06 07:29:48

如果source是一个object变量,那么instanceof就是一种检查它是否是Button的方法。

票数 14
EN

Stack Overflow用户

发布于 2014-12-14 02:42:16

代码语言:javascript
复制
public class Animal{ float age; }

public class Lion extends Animal { int claws;}

public class Jungle {
    public static void main(String args[]) {

        Animal animal = new Animal(); 
        Animal animal2 = new Lion(); 
        Lion lion = new Lion(); 
        Animal animal3 = new Animal(); 
        Lion lion2 = new Animal();   //won't compile (can't reference super class object with sub class reference variable) 

        if(animal instanceof Lion)  //false

        if(animal2 instanceof Lion)  //true

        if(lion insanceof Lion) //true

        if(animal3 instanceof Animal) //true 

    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7313559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档