什么是“实例”? Java 中使用的运算符?
instanceof
运算符的用途是什么?我见过类似的东西
if (source instanceof Button) {
//...
} else {
//...
}
,但对我来说没有任何意义。我已经完成了研究,但只提供了示例,没有任何解释。
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
如果表达式的左侧是右侧类名的实例,则该运算符返回 true。
这样想吧。假设您所在街区的所有房屋都是按照相同的蓝图建造的。十栋房子(对象),一套蓝图(类定义)。
当您拥有一组对象但不确定它们是什么时,
instanceof
是一个有用的工具。假设您在表单上有一组控件。您想要读取那里的任何复选框的选中状态,但您不能向普通的旧对象询问其选中状态。相反,您会查看每个对象是否是一个复选框,如果是,则将其转换为复选框并检查其属性。It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.如此网站所述:
我希望这有帮助!
As described on this site:
I hope this helps!
该运算符允许您确定对象的类型。
它返回一个布尔值。
例如
输出是:
This operator allows you to determine the type of an object.
It returns a
boolean
value.For example
the output is:
如果
source
是一个object
变量,则instanceof
是一种检查它是否是Button
的方法。If
source
is anobject
variable,instanceof
is a way of checking to see if it is aButton
or not.正如其他答案中提到的,
instanceof
的规范典型用法是检查标识符是否引用更具体的类型。示例:但请注意,左侧表达式的类型必须是右侧表达式的父类型(请参阅JLS 15.20.2 和 Java Puzzlers,#50,第 114 页)。例如,以下内容将无法编译:
编译失败,并显示消息:
As
Test
is not aparent class ofString
。 OTOH,这可以完美编译并按预期打印false
:As mentioned in other answers, the canonical typical usage of
instanceof
is for checking if an identifier is referring to a more specific type. Example:Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
This fails to compile with the message:
As
Test
is not a parent class ofString
. OTOH, this compiles perfectly and printsfalse
as expected:大多数人都正确解释了这个问题的“什么”,但没有人正确解释“如何”。
所以这里有一个简单的说明:
输出:
将
s
与 StringBuffer 进行比较时编译器错误的原因在 文档:这意味着 LHS 必须是 RHS 的实例,或者是实现 RHS 或扩展 RHS 的类的实例。
那么如何使用use instanceof呢?
由于每个类都扩展了对象,因此将 LHS 类型转换为对象将始终对您有利:
输出:
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
Outputs:
The reason for compiler error when comparing
s
with StringBuffer is well explained in docs:which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
Outputs:
最好的解释是 jls。
始终尝试检查消息来源的说法。在那里您将得到最好的答案以及更多。
在这里复制一些部分:
Best explanation is jls.
Always try to check what source says. There you will get the best answer plus much more.
Reproducing some parts here:
http://download.oracle.com/javase/tutorial/java/nutsandbolts /op2.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
当您想了解特定对象的实例时,Instance of 关键字很有帮助。
假设您抛出异常,当您捕获时,执行 sum 自定义操作,然后再次按照您的逻辑继续(抛出或日志等)
示例:
1) 用户创建了自定义异常“InvalidExtensionsException”并按照逻辑抛出它
2) 现在在 catch 块中
捕获(异常e){
如果异常类型为“InvalidExtensionsException”,则执行求和逻辑
3) 如果您不检查实例且异常类型为空指针异常,您的代码将中断。
所以你的逻辑应该在实例内部
if (e实例InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
上面
的例子是错误的编码实践,但是这个例子可以帮助您理解它的实例的使用。
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
java
instanceof
运算符用于测试对象是否是指定类型(类或子类或接口)的实例。java中的instanceof也称为类型比较运算符,因为它将实例与类型进行比较。它返回
true
或false
。如果我们将instanceof
运算符应用于任何具有null
值的变量,它将返回false
。从包含 JEP 305 的 JDK 14+ 开始,我们还可以对
进行“模式匹配” instanceof
模式基本上测试一个值是否具有某种类型,并且当它具有匹配的类型时可以从该值中提取信息。
模式匹配允许更清晰、更有效地表达系统中的通用逻辑,即有条件地从对象中删除组件。
Java 14之前
Java 14增强功能
我们还可以将类型检查和其他条件结合在一起
在
instanceof
中使用模式匹配应该可以减少总数Java 程序中的显式强制转换。PS:
instanceOf
只有在对象不为null时才会匹配,然后才可以赋值给str
。The java
instanceof
operator is used to test whether the object is an instance of the specified type (class or subclass or interface).The instanceof in java is also known as type
comparison operator
as it compares the instance with type. It returns eithertrue
orfalse
. If we apply theinstanceof
operator with any variable that hasnull
value, it returnsfalse
.From JDK 14+ which includes JEP 305 we can also do "Pattern Matching" for
instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Pattern matching allows a more clear and efficient expression of common logic in a system, namely the conditional removal of components from objects.
Before Java 14
Java 14 enhancements
We can also combine the type check and other conditions together
The use of pattern matching in
instanceof
should reduce the overall number of explicit casts in Java programs.PS:
instanceOf
will only match when the object is not null, then only it can be assigned tostr
.可以用作相等检查的简写。
所以这段代码
可以写成
Can be used as a shorthand in equality check.
So this code
can be written as
当对象(listObj)中存在的元素类型在运行时未知时,也可以使用 instanceof 运算符。在这些情况下,instanceof 运算符可用于确定元素类型,并将有助于根据要求进一步进行操作。
例如:
如果从对象检索的值分配给一个变量,JVM 会要求您在编译时将其转换为特定类型。
让我们考虑一下:
// 在上面的示例中,从 listObj 检索的元素是 String 并被转换为 int。这将解决编译时错误。但是在执行时JVM将抛出ClassCastException。
因此,我们可以使用instanceof运算符来检查并将值分配给正确的变量,以避免错误,而不是随机分配值给与类型不匹配的变量。
instanceof operator can also be used when the type of the elements present in the object(listObj) is unknown at run time. In those cases instanceof operator can be used to figure out the elements type and will be helpful to proceed further based on the requirement.
For Example :
if the value retrieved from the object is assigned to a variable,JVM will ask you to cast it to a particular type at compile time.
lets consider :
// In above example , element retrieved from listObj is String and is casted to int. This will resolve the compile time errors.But at the time of execution JVM will throw ClassCastException.
so instead of randomly assigning values to a variable that does not matches the type, we can use instanceof operator to check and assign the values to the correct variables to avoid errors.
非常简单的代码示例:
这里要小心。在上面的示例中,如果 Class1 是 Object,则第一次比较将始终为 true。因此,就像例外一样,等级顺序很重要!
Very simple code example:
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
您可以使用 Map 对实例进行更高的抽象
然后让这样的映射向其添加一些操作:
然后如果有一个未知类型的对象,您可以从该映射中获取特定的操作:
You could use Map to make higher abstraction on instance of
Then having such map add some action to it:
Then having an Object of not known type you could get specific action from that map:
instanceof 运算符用于检查对象是否是指定类型的实例。 (类或子类或接口)。
instanceof 也称为类型比较运算符,因为它将实例与类型进行比较。它返回 true 或 false。
如果我们对任何具有 null 值的变量应用 instanceof 运算符,它将返回 false。
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
If we apply the instanceof operator with any variable that has null value, it returns false.
instanceof
关键字是一个二元运算符,用于测试对象(实例)是否是给定类型的子类型。想象一下:
想象一个
狗
对象,用Objectdog = new Dog()
创建,然后:但是,用
Objectanimal=new 创建Animal();
,因为
Animal
是Dog
的超类型,并且可能不太“精致”。而且,
这是因为
Dog
既不是Cat
的子类型,也不是 Cat 的超类型,并且它也没有实现它。请注意,上面用于在运行时根据对象类型做出不同的反应 。
dog
的变量是Object
类型。这是为了表明instanceof
是一个运行时操作,并将我们带到一个/用例:需要注意的是:对于所有类型
T
,expressionThatIsNull instanceof T
都是 false。instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.Imagine:
Imagine a
dog
object, created withObject dog = new Dog()
, then:However, with
Object animal = new Animal();
,because
Animal
is a supertype ofDog
and possibly less "refined".And,
This is because
Dog
is neither a subtype nor a supertype ofCat
, and it also does not implement it.Note that the variable used for
dog
above is of typeObject
. This is to showinstanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.Things to note:
expressionThatIsNull instanceof T
is false for all TypesT
.