How to Use the instanceof Operator with a Generic Class in Java
See Java: Tips and Tricks for similar articles.
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.
- Open your text editor and type in the following Java statements:
The program instantiates two objects of type GenericInstanceof. TheGenericInstanceofclass is defined starting at line 10. Notice the use of theinstanceofkeyword to identify the type of argument passed to theidentifymethod. The main method calls theidentifymethod for each object. - Save your file as UseinstanceofOperatorWithAGenericClass.java.
- 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.

- 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.

