instanceof cannot be interfaced. The reason is: the instanceof keyword is used to check whether an object is an instance of a specific class, and cannot be directly used to check whether an object is an instance of an interface, because the interface cannot be instantiated.
Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Java, the instanceof keyword is used to check whether an object is an instance of a specific class. It cannot be used directly to check whether an object is an instance of an interface because interfaces cannot be instantiated. However, there are some indirect ways to check whether an object implements an interface.
First, we need to understand generics and type erasure in Java. In Java, generics are a mechanism used for type checking at compile time. It allows you to check whether variables, parameters, return types, etc. conform to specified types at compile time. Type erasure is a mechanism that erases generic type information at compile time, so that the runtime code does not know the generic type information.
In Java, you can use generics and type erasure to create a collection that can accept any type, such as List
In this way, we can check whether an object implements an interface at runtime. For example, we can create a method that accepts a List
The following is a simple sample code that demonstrates how to use generics and type erasure to check whether an object implements a certain interface:
import java.util.List; public class InstanceOfInterfaceExample { public static <T> T findFirstInstance(List<Object> list, Class<T> interfaceClass) { for (Object obj : list) { if (interfaceClass.isInstance(obj)) { return interfaceClass.cast(obj); } } return null; } }
In this example, the findFirstInstance method accepts A List
The above is the detailed content of Why instanceof can interface. For more information, please follow other related articles on the PHP Chinese website!