getClass
method and the Class
class.Table of Contents
- Introduction
- Using
getClass().getName()
- Using
Class.getName()
- Getting the Simple Class Name
- Conclusion
Introduction
Java provides several methods to get the name of a class. These methods are useful in various scenarios, such as logging the class name for debugging purposes or performing operations using reflection.
Using getClass().getName()
The getClass().getName()
method is used to get the class name of an object. This method is called on an instance of the class.
Example
public class ClassNameExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
String className = myObject.getClass().getName();
System.out.println("Class name: " + className);
}
}
class MyClass {
// Class implementation
}
Explanation
myObject.getClass()
: Returns the runtime class of the objectmyObject
.getClass().getName()
: Returns the fully qualified name of the class.
Output:
Class name: MyClass
Using Class.getName()
You can also get the class name directly from the class itself using Class.getName()
.
Example
public class ClassNameExample {
public static void main(String[] args) {
String className = MyClass.class.getName();
System.out.println("Class name: " + className);
}
}
class MyClass {
// Class implementation
}
Explanation
MyClass.class
: Obtains theClass
object associated with theMyClass
.class.getName()
: Returns the fully qualified name of the class.
Output:
Class name: MyClass
Getting the Simple Class Name
If you are only interested in the simple name of the class (i.e., without the package name), you can use the getSimpleName()
method.
Example
public class ClassNameExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
String simpleClassName = myObject.getClass().getSimpleName();
System.out.println("Simple class name: " + simpleClassName);
}
}
class MyClass {
// Class implementation
}
Explanation
getClass().getSimpleName()
: Returns the simple name of the class (without the package name).
Output:
Simple class name: MyClass
Conclusion
Obtaining the class name in Java can be accomplished using various methods, including getClass().getName()
, Class.getName()
, and getClass().getSimpleName()
. Each method has its own advantages and specific use cases:
- The
getClass().getName()
method is useful when you have an instance of the class. - The
Class.getName()
method is useful when you are working directly with the class. - The
getClass().getSimpleName()
method is useful when you need only the simple name of the class without the package name.
By understanding these methods, you can choose the most appropriate one for your specific use case when working with class names in Java.
Comments
Post a Comment
Leave Comment