Have you ever touched instanceof, isInstance, isAssignableFrom, or some of them?

define

a instanceof B

A is an instance of B, and B is a class or interface, parent class or parent interface.

B.class.isInstance(a)

Dynamic equivalence is used to check generic types, such as keys and values in a CheckedMap.

A.class.isAssignableFrom(B)

The type relationship between two classes determines whether B is A subclass or subinterface of A

demo

Take a look at the following examples to see what each of them is used for and what they mean.

User: User base class

PrivateUser: a PrivateUser subclass that inherits the User class

PrivateUser priUser = new PrivateUser(); System.out.println(priUser instanceof User); // true System.out.println(User.class.isInstance(priUser)); // true System.out.println(User.class.isAssignableFrom(PrivateUser.class)); // true System.out.println(PrivateUser.class.isAssignableFrom(User.class)); // falseCopy the code

Read more on my blog:

1.Java JVM, Collections, Multithreading, new features series tutorials

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Java, backend, architecture, Alibaba and other big factory latest interview questions

Life is good. See you tomorrow