To find the class of an object in Java, you can use the getClass()
method from the Object
class.
The getClass()
method returns a Class
object that represents the runtime class of the object. The Class
object contains information about the object's class, including its name, fields, methods, and other metadata.
Here's an example of how to find the class of an object in Java:
String str = "Hello, world!"; Class cls = str.getClass(); System.out.println("The class of the object is " + cls.getName());
In the above example, a String
object is created and stored in the str
variable. The getClass()
method is then called on the str
object and the result is stored in the cls
variable.
The getName()
method is called on the cls
object to get the name of the class as a String
. The name of the class is then printed to the console.
In this example, the output will be "The class of the object is java.lang.String", since the object is an instance of the String
class.
You can also use the isInstance()
method from the Class
object to check if an object is an instance of a specific class or a subclass of that class.
For example:
if (cls.isInstance(str)) { System.out.println("The object is an instance of the " + cls.getName() + " class"); }
In this example, the isInstance()
method is called on the cls
object and passed the str
object as an argument. If the str
object is an instance of the class represented by cls
, the if
statement is executed and a message is printed to the console.