How to Use the instanceof Operator with a Generic Class in Java

From time to time you might want to know the data type of a parameter passed to method in a Java generic class. For example, imagine that you wish to write a method to identify whether a String or an Integer was received as an argument. You could accomplish this task using the instanceof operator. To learn how to use the instanceof operator with a Java generic class, follow these four steps.

  1. Open your text editor and type in the following Java statements:
    Java Source for instanceof Generic
    The program instantiates two objects of type GenericInstanceof. The GenericInstanceof class is defined starting at line 10. Notice the use of the instanceof keyword to identify the type of argument passed to the identify method. The main method calls the identify method for each object.
  2. Save your file as
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
    Compile Source for instanceof Generic
  4. Type in the command to run your program and hit Enter. Notice in the output that the String variable and the Integer variable were each identified by the generic class.
    Run for instanceof Generic
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.