- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to display Object class using instanceOf keyword in Java
Problem Description
How to display Object class using instanceOf keyword?
Solution
This example makes displayObjectClass() method to display the Class of the Object that is passed in this method as an argument.
import java.util.ArrayList; import java.util.Vector; public class Main { public static void main(String[] args) { Object testObject = new ArrayList(); displayObjectClass(testObject); } public static void displayObjectClass(Object o) { if (o instanceof Vector) System.out.println( "Object was an instance of the class java.util.Vector"); else if (o instanceof ArrayList) System.out.println( "Object was an instance of the class java.util.ArrayList"); else System.out.println("Object was an instance of the " + o.getClass()); } }
Result
The above code sample will produce the following result.
Object was an instance of the class java.util.ArrayList
java_methods.htm
Advertisements