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.pswp.cn/news/371189.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371189.shtml
英文地址,請注明出處:http://en.pswp.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…