1. Introduction

In Java, a strongly typed language, type conversion and type judgment are often encountered. Today, let’s take a closer look at the methods of type determination in Java.

2. instanceof

Instanceof is a Java operator that determines whether an object is an instanceof a class. Usage:

boolean isInstance = obj instanceof Class
Copy the code

Where obj is an instance of an object, Class is the name of a Class or an interface, and obj is an instance of Class, a subclass of Class, or an implementation of its interface, return true, or false.

Note that obj must be a reference type, not a primitive type.

int integer = 0;
// An error will be reported during compilation
boolean isInstance = integer instanceof Number
Copy the code

In addition, the compiler checks to see if the obj in the instanceof expression can be converted to the Class type on the right. If it cannot be converted, an error is reported. If the type cannot be determined, the compiler will also pass the compilation.

3. Class.isInstance

   // class. isInstance is equivalent to the instanceof operator
  boolean ret = entity instanceof UserInfo;
  boolean isInstance = UserInfo.class.isInstance(entity);
Copy the code

As shown above, class.isinstance is equivalent to the instanceof operator. This method was introduced in Java 1.1 because it can be used dynamically. Returns true if the argument is not null and can be successfully cast to the reference type on the left without raising a ClassCastException.

4. Class.isAssignableFrom

The caller and arguments to this method are Class objects, the caller is the parent Class, and the arguments are themselves or their subclasses.

boolean assignableFrom = List.class.isAssignableFrom(ArrayList.class);
Copy the code

This method is used to determine whether a class is the implementation of an interface.

5. Class.isPrimitive

This method is used to determine whether the Class is primitive (Boolean, char, byte, short, int, long, float, double).

//true
boolean primitive = int.class.isPrimitive();
Copy the code

It is designed to solve the basic type judgment problem we mentioned in Section 2 of this article. But it can only determine whether a type is a base type, not specific to a type.

Note, however, that this method returns false for the wrapper type of the underlying type.

6. Summary

In addition to the first two types being common, the latter two types are of limited use. I wonder which of these have you used? Welcome to comment. I am: code farmer small fat brother, more attention, more knowledge to share.