Java instead of 用法_我又不是你的谁--java instanceof操作符用法揭秘

背景故事

《曾经最美》是朱铭捷演唱的一首歌曲,由陈佳明填词,叶良俊谱曲,是电视剧《水晶之恋》的主题曲。歌曲时长4分28秒。 歌曲歌词:

看不穿你的眼睛

藏有多少悲和喜

像冰雪细腻又如此透明

仿佛片刻就要老去

整个城市的孤寂

不止一个你

只能远远的

想像慰藉我们之间的距离

我又不是你的谁

不能带给你安慰

忍心你枯萎凋零的玫瑰

仿佛希望化成灰

要不是痛彻心扉

谁又记得谁

只是云和月

相互以为是彼此的盈缺

不能哭喊已破碎

曾经的最美

独自一个人熟悉的街

别问你在想谁

不去追悔已憔悴

爱过的机会

真实已粉碎人事已非

还有什么最可贵

我又不是你的谁

不能带给你安慰

忍心你枯萎凋零的玫瑰

仿佛希望化成灰

要不是痛彻心扉

谁又记得谁

只是云和月

相互以为是彼此的盈缺

不能哭喊已破碎

曾经的最美

独自一个人熟悉的街

别问你在想谁

不去追悔已粉碎

爱过的机会

真实已粉碎人事已非

还有什么最可贵

不能哭喊已破碎

曾经的最美

独自一个人熟悉的街

别问你在想谁

不去追悔已憔悴

爱过的机会

真实已粉碎人事已非

还有什么最可贵

牵线之牛刀小试

如何判断是不是谁的谁?java有一个instanceof操作符(关系操作符)可以做这件事。

public static voidmain(String[] args) {

String s= "Hello World!";

System.out.println(sinstanceofString);

}

打印出结果true

可是如果你的哪个谁不存在呢?请看代码:

public static voidmain(String[] args) {

String s= null;

System.out.println(sinstanceofString);

}

很多人都会异口同声的说

false

e5aac2cc21dfe721e1f4c826c3c0a7ba.gif

你答对了。

JSL-15.20.2规定

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

牵线之乱点鸳鸯谱

如果没有任何关系的两个类使用instanceof会如何?

class Point { intx, y; }class Element { intatomicNumber; }public classInstanceofTest {public static voidmain(String[] args) {

Point p= newPoint();

Element e= newElement();if (e instanceof Point) {

System.out.println("匹配成功!");

}else{

System.out.println("匹配不成功");

}

}

}

不少人会说:“匹配不成功”

3fde01d0d8d9f609fb0686e542c47d8c.gif

抱歉,你又掉进坑里了,这个会报编译错误

00c0170e1e5fbd75069a848d61abf002.png

JSL-15.20.2规定

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type, or a compile-time error occurs.

It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reference type that is reifiable (§4.7).

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error (§15.16), then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

当然,cast也会是编译错误

class Point { intx, y; }class Element { intatomicNumber; }public classInstanceofTest {public static voidmain(String[] args) {

Point p= newPoint();

Element e= newElement();

p= (Point)e; //compile-time error

}

}

牵线之暗藏玄机

编译器并不是万能的,并不能检测出所有问题,看下面:

class Point { intx, y; }class Element { intatomicNumber; }public classInstanceofTest {public static voidmain(String[] args) {

Point p= newPoint();//Element e = new Element();

p = (Point) newObject();

System.out.println(pinstanceofPoint);

}

}

猛一看,没事问题,编译也没有问题,可是运行时报错

Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to Point

上面的程序展示了当要被转型的表达式的静态类型是转型类型的超类时,转型操作符的行为。与instanceof 操作相同,如果在一个转型操作中的两种类型都是类,那么其中一个必须是另一个的子类型。尽管对我们来说,这个转

型很显然会失败,但是类型系统还没有强大到能够洞悉表达式new Object()的运行期类型不可能是Point的一个子类型。因此,该程序将在运行期抛出ClassCastException 异常。

牵线之竞争激烈

关系操作符instanceof可不是市场上唯一的选择,另外一个背靠大山的家伙要注意了

Class 的方法

booleanisInstance(Object obj)

Determines if the specified Object is assignment-compatible with the object represented by this Class.

那么什么时候该用instanceof 什么时候该用isInstance呢

我的理解是

instanceof偏向于比较class之间

isInstance偏向于比较instance和class之间

stackoverflow也有此问题的解答:

I take that to mean that isInstance() is primarily intended for use in code dealing with type reflection at runtime. In particular, I would say that it exists to handle cases where you might not know in advance the type(s) of class(es) that you want to check for membership of in advance (rare though those cases probably are).

For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:

public booleanareObjectsAssignable(Object left, Object right) {returnleft.getClass().isInstance(right);

}

In general, I'd say that using instanceof should be preferred whenever you know the kind of class you want to check against in advance. In those very rare cases where you do not, use isInstance() instead.

参考资料

【1】https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.20.2

【2】java解惑

【3】https://stackoverflow.com/questions/8692214/when-to-use-class-isinstance-when-to-use-instanceof-operator

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371189.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

3.26

http://codeforces.com/gym/101196/attachments A题 B题 题意:一群人玩桌上足球(>4人),分成黑白两队,每队有进攻和防守两名玩家,如果有一方失败则失败方的防守坐到等候席的结尾、进攻被流放到防守区再上来一个人作为进攻方。而…

scala akka通信机制

https://www.2cto.com/kf/201701/587514.html转载于:https://www.cnblogs.com/rocky-AGE-24/p/7542874.html

JUnit通过失败测试案例

为什么要建立一种预期测试失败的机制? 有一段时间,人们会希望并期望JUnit Test案例失败。 尽管这种情况很少见,但确实发生了。 我需要检测JUnit测试何时失败,然后(如果期望的话)通过而不是失败。 具体情况是…

CentOS6.5安装MySQL5.7详细教程

CentOS6.5安装MySQL5.7详细教程 注:文中所写的安装过程均在CentOS6.5 x86下通过测试 主要参考博文: https://segmentfault.com/a/1190000003049498 http://www.th7.cn/db/mysql/201601/175073.shtml 1.检测系统是否已经安装过mysql或其依赖,若…

cmake 查看编译命令,以及在vscode中如何使用cmke

通过设置如下配置选项,可以生成compile_commands.json 文件,记录使用的编译命令 set(CMAKE_EXPORT_COMPILE_COMMANDS ON)获得现有模块列表 cmake --help-module-list查看命令文档 cmake --help-command find_file查看模块的详细信息 cmake --help-mo…

php学习八:封装

一:在php中,用class关键字来创建一个类,即进行封装;在类里面有成员属性和方法行为组成: 1.成员属性:用关键字var来声明,可以给初始值也可以不给;现在var废弃,用public来声明,public为共有属性&a…

纯Java JavaFX 2.0菜单

在有关JavaFX的最新文章中 ,我集中讨论了不使用JavaFX 1.x的JavaFXScript和不使用JavaFX 2.0的新FXML来使用JavaFX 2.0的新Java API 。 所有这些示例均已使用标准Java编译器进行了编译,并使用标准Java启动 器执行。 在本文中,我将继续演示使用…

设置QtreeWidget水平滚动条

转载请注明出处:http://www.cnblogs.com/dachen408/p/7552603.html //设置treewidget水平滚动条 ui.treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);ui.treeWidget->header()->setStretchLastSection(false);转载于:https…

java 序列化 uid,Java中的序列化版本uid

How is Serialization id stored in the instance of the object ?The Serialization id we declare in Java is static field;and static fields are not serialized.There should be some way to store the static final field then. How does java do it ?解决方案The ser…

HTML5本地存储

什么是Web Storage Web Storage是HTML5里面引入的一个类似于cookie的本地存储功能,可以用于客户端的本地存储,其相对于cookie来说有以下几点优势: 存储空间大:cookie只有4KB的存储空间,而Web Storage在官方建议中为每个…

番石榴秒表

番石榴的秒表是番石榴第10版的另一个新番石榴类(作为Optional ,这是另一篇近期文章的主题)。 顾名思义,这个简单的类提供了一种方便地测量两个代码点之间经过的时间的方法。 与使用System.currentTimeMillis(&#xff…

CF 839 E-最大团

CF 839 E Soltion: 就是怎么求最大团的问题: 以下是\(O(7000\times n^2)\)的做法 求一个最大团,然后将所有的药水平均分配,到最大团的所有点上,计算答案. #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorit…

sse java_SSE详解

SSE(Server-Sent Events):通俗解释起来就是一种基于HTTP的&#xff0c;以流的形式由服务端持续向客户端发送数据的技术应用场景由于HTTP是无状态的传输协议,每次请求需由客户端向服务端建立连接,HTTPS还需要交换秘钥&#xff0c;所以一次请求,建立连接的过程占了很大比例在http…

520. Detect Capital

题目&#xff1a; Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA".A…

盒模型的属性丶display显示丶浮动

一丶盒模型的属性(重要) 1.padding padding是标准文档流,父子之间调整位置 <!DOCTYPE html><html><head><meta charset"UTF-8"><title>padding</title><style>*{padding: 0;margin: 0;}.box{width: 200px;height: 200px;b…

MapReduce:通过数据密集型文本处理

自上次发布以来已经有一段时间了&#xff0c;因为我一直在忙于Coursera提供的一些课程。 有一些非常有趣的产品&#xff0c;值得一看。 前一段时间&#xff0c;我购买了Jimmy Lin和Chris Dyer的MapReduce数据密集型处理程序 。 本书以伪代码格式介绍了几种关键的MapReduce算法。…

ubuntu(deepin)安装apache2并支持php7.0

linux虚拟机下用于开发环境测试&#xff0c;安装的apache和php7.0&#xff0c;但是简单安装完两者后apache并不能解析php&#xff0c;原因是确实apache的php扩展。 # 首先安装apache sudo apt-get install apache2 # 然后安装php7.0 sudo apt-get install php7.0 # 一般执行完这…

java applet 换行_Java复习题

一、选择题1.有Java语句如下&#xff0c;则说法正确的是()A.此语句是错误的B. a.length的值为5C. b.length的值为5D. a.length和b.length的值都为52.整数除法中&#xff0c;如果除数为0&#xff0c;则将导致的异常是( B )A. NullPointerExceptionB. ArithmeticExceptionC. Arra…

解决:MVC对象转json包含\r \n

项目中对象转json字符串时&#xff0c;如下&#xff1a;JsonSerializerSettings jsetting new JsonSerializerSettings(); jsetting.DefaultValueHandling DefaultValueHandling.Ignore; return JsonConvert.SerializeObject(resultMoldels, Formatting.Indented, jsetting);…

CSS 小结笔记之滑动门技术

所谓的滑动门技术&#xff0c;就是指盒子背景能够自动拉伸以适应不同长度的文本。即当文字增多时&#xff0c;背景看起来也会变长。 大多数应用于导航栏之中&#xff0c;如微信导航栏: 具体实现方法如下&#xff1a; 1、首先每一块文本内容是由a标签与span标签组成 <a hr…