[英]What is the easiest way to do 'is' in Java?
許多語言都有檢查Object是否屬於某種類型(包括父類)的工具,用'is'實現並使用如下:
if(obj is MyType)
或者稍微繁瑣一點,您可以在其他語言中使用'as'關鍵字進行檢查,以進行軟類型轉換並查看結果是否為null。
我多年沒有使用Java了,而且我正在快速恢復它,但是Java有一種方法可以輕松地完成這項工作而無需深入研究Reflection API嗎?
提前感謝您的回答。 我在這里和其他地方搜索過,但所涉及的關鍵詞非常通用,即使我確定這有一個簡單的答案,谷歌搜索它很難。
if (objectReference instanceof type){
//Your code goes here
}
更多信息在這里 。
您只能將instanceof
與類文字一起使用:即:
Class type = String.class;
if (myObj instanceof String) // will compile
if (myObj instanceof type) //will not compile
另一種方法是使用方法Class.isInstance
if (type.isInstance(myObj)) // will compile
obj instanceof TargetType
僅在TargetType
位於包含obj
的類型層次結構中時返回true。
請參閱Sun的教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.