Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analyze the Java keyword instanceof

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "analyzing the Java keyword instanceof". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Instanceof is strictly a binocular operator in Java to test whether an object is an instance of a class, using:

Boolean result = obj instanceof Class

Where obj is an object, and Class represents a class or an interface. When obj is the object of Class, or its direct or indirect subclass, or the implementation class of its interface, the result result returns true, otherwise it returns false.

Note: the compiler will check whether obj can be converted to the class type on the right. If it cannot be converted, the error will be reported directly. If the type is not determined, it will be compiled, depending on the runtime.

1. Obj must be a reference type, not a basic type int I = 0position system. Out.println (i instanceof Integer); / / compilation does not pass System.out.println (i instanceof Object); / / compilation does not pass

The instanceof operator can only be used to judge an object.

2. Obj is nullSystem.out.println (null instanceof Object); / / false

Descriptions of null types are described in the official documentation. We generally know that Java is divided into two data types, one is the basic data type, there are eight are byte short int long float double char boolean, and the other is the reference type, including classes, interfaces, arrays, and so on. There is also a special null type in Java, which does not have a name, so it is impossible to declare as a variable of type null or convert to a null type. Null references are the only possible values for null type expressions, and null references can also be converted to any reference type. We don't need to know much about null types, we just need to know that null is a special symbol that can be any reference type.

The instanceof operator in the JavaSE specification states that if obj is null, false will be returned.

3. Obj is the instance object of class class Integer integer = new Integer (1); System.out.println (integer instanceof Integer); / / true

There's nothing to say. It's the most common use.

4. Obj is the implementation class of class interface.

If you know about the Java collection, we know that there is an upper interface List in the collection, which has a typical implementation class ArrayList

Public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable

So we can use the instanceof operator to determine whether an object is an implementation class of the List interface. If it returns true, it returns false.

ArrayList arrayList = new ArrayList (); System.out.println (arrayList instanceof List); / / true

Or vice versa, return true

List list = new ArrayList (); System.out.println (list instanceof ArrayList); / / true5, obj are direct or indirect subclasses of the class class

We create a new parent class, Person.class, and then create a subclass of it, Man.class

Public class Person {}

Man.class

Public class Man extends Person {}

Test:

Person p1 = new Person (); Person p2 = new Man (); Man M1 = new Man (); System.out.println (p1 instanceof Man); / / falseSystem.out.println (p2 instanceof Man); / / trueSystem.out.println (M1 instanceof Man); / / true

Note that in the first case, p1 instanceof Man, Man is a subclass of Person, and Person is not a subclass of Man, so the return result is false.

6. Problems

As we said earlier, the compiler will check whether obj can be converted to the class type on the right. If it cannot be converted, it will report an error directly. If the type is not determined, it will be compiled, depending on the runtime.

Look at the following examples:

Person p1 = new Person (); System.out.println (p1 instanceof String); / / compile error System.out.println (p1 instanceof List); / / falseSystem.out.println (p1 instanceof List); / / falseSystem.out.println (p1 instanceof List); / / compile error

According to what we said above, there is a problem here. The Person object p1 obviously cannot be converted into a String object, so the natural Person object p1 instanceof String cannot be compiled, but why can the p1 instanceof List be compiled? And instanceof List can't be compiled?

7. Delve into the principle

We can take a look at the Java language specification Java SE 8: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2

If you describe it in pseudo code:

Boolean result;if (obj = = null) {result = false;} else {try {T temp = (T) obj; / / checkcast result = true;} catch (ClassCastException e) {result = false;}}

That is to say, the type of the obj Operand with the expression obj instanceof Tjurisdiction instanceof operator must be a reference type or an empty type; otherwise, a compile-time error will occur.

If a compilation error occurs when obj is cast to T, the instanceof of the relational expression also generates a compile-time error. In this case, the result of the expression instance is always false.

At run time, if the value of T is not null and obj can be converted to T without throwing a ClassCastException, the result of the instanceof operator is true. Otherwise, the result is wrong.

To put it simply: if obj is not null and (T) obj does not throw a ClassCastException exception, the expression value is true, otherwise the value is false.

So it's easy to understand why p1 instanceof String compiles an error, because (String) p1 cannot be compiled, and (List) p1 can be compiled.

8. The implementation strategy of instanceof

Implementation algorithm of JavaSE 8 instanceof: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.instanceof

1. If obj is null, return false;. Otherwise, set S to the type object of obj. The remaining problem is to check whether S is a subtype of T.

2. If S = T, return true

3. The next three cases are divided into three cases, because what instanceof needs to do is "subtype checking", while the subtype rules of array types, interface types and ordinary class types in the type system of Java language are different and must be discussed separately.

①, S are array types: if T is a class type, then T must be Object;. If T is an interface type, then T must be one of the interfaces implemented by the array.

②, interface type: for the instanceof of the interface type, directly traverse the interface recorded in S to see if it is consistent with T

③, class type: the instanceof of the class type traverses the super chain (inheritance chain) of S to Object to see if it is consistent with T. Traversing the super chain of a class means that the performance of this algorithm is affected by the depth of inheritance of the class.

This is the end of "analyzing the Java keyword instanceof". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report