Java Object getClass() Method
The Object getClass() method is used to obtain the runtime class of an object.
Syntax
object.getClass()
Parameters
-
None .
Return Value
Returns the class of the object.
Example
The following example demonstrates the use of the getClass() method; String and ArrayList inherit from Object, so they can use the getClass() method directly:
Example
import
java
.
util
.
ArrayList
;
class
RunoobTest
{
public
static
void
main
(
String
[
]
args
)
{
//
getClass() with Object
Object
obj1
=
new
Object
(
)
;
System
.
out
.
println
(
"
The class of obj1 is:
"
obj1
.
getClass
(
)
)
;
//
getClass() with String
String
obj2
=
new
String
(
)
;
System
.
out
.
println
(
"
The class of obj2 is:
"
obj2
.
getClass
(
)
)
;
//
getClass() with ArrayList
ArrayList
<
Integer
obj3
=
new
ArrayList
<>
(
)
;
System
.
out
.
println
(
"
The class of obj3 is:
"
obj3
.
getClass
(
)
)
;
}
}
The execution result of the above program is:
obj1 的类为: class java.lang.Object
obj2 的类为: class java.lang.String
obj3 的类为: class java.util.ArrayList
Custom class calling the getClass() method:
Example
class
RunoobTest
{
public
static
void
main
(
String
[
]
args
)
{
//
Create an object of the RunoobTest class
RunoobTest
obj
=
new
RunoobTest
(
)
;
//
RunoobTest inherits from the Object class; Object is the superclass of all classes
//
Call the getClass() method
System
.
out
.
println
(
obj
.
getClass
(
)
)
;
}
}
The execution result of the above program is:
class RunoobTest
Java Object Class