Home  >  Article  >  Java  >  In this way, the instanceof keyword can be implemented

In this way, the instanceof keyword can be implemented

巴扎黑
巴扎黑Original
2017-07-18 18:28:041335browse
If you use Java pseudocode to express the runtime semantics described in the Java language specification, it will be like this:
// obj instanceof Tboolean result;if (obj == null) {
  result = false;
} else {  try {
      T temp = (T) obj; // checkcast  result = true;
  } catch (ClassCastException e) {
      result = false;
  }
}

Said in Chinese That is: if there is an expression obj instanceof T, then if obj is not null and (T) obj does not throw a ClassCastException exception, the value of the expression is true, otherwise the value is false.
Note that there is no mention of JVM or Class objects at all, and it does not show how to obtain the type of T from the perspective of code. Also note that the instanceof operator has some compile-time restrictions in addition to runtime semantics. Please refer to the specification for details.


Instanceof is a binary operator in Java, which is the same type as ==, >, <. Since it is composed of letters, it is also a reserved keyword in Java. Its function is to test whether the object on its left is an instance of the class on its right, and return boolean type data

The instanceof
operator in java is used to indicate whether the object is a specific class at runtime an instance of. instanceof returns a Boolean value indicating whether the object is an instance of this specific class or a subclass of it.

Usage:
result = object instanceof class
Parameters:
Result: Boolean type.

Object: required. Any object expression.
Class: required. Any defined object class.
Description:
If object is an instance of class
, the instanceof operator returns true. Returns false if object is not an instance of the specified class, or if object is null.

The above is the detailed content of In this way, the instanceof keyword can be implemented. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn