getclass() method in java

In this article, we will discuss the getclass() method in java.
Here is the table content of the article will we will cover this topic.

1. What is getclass() method in java?
2. What is the use of getClass() method? OR Need of getclass() method?

What is getclass() method in java?

The getClass() method is defined in the Object class which is the super most class in Java. This method returns the object of the Class class.  As you know String, Array, etc are classes in java. In the same manner ”Class” is also a class in Java. It returns the runtime class of this object. This method is also a native method. It is a final method, so we can’t override it.

Let’s have a look at the code.

public final native Class<?> getClass();

It is a native method. By means of the native method, it is written in C/C++ language.

public class Example 
{
	public static void main(String[] args) 
	{
		Example obj = new Example();
		Class objOfClass = obj.getClass();
		System.out.println(objOfClass);
	}
}
public class Example 
{
	public static void main(String[] args) 
	{
		Example obj = new Example();
		Class objOfClass = obj.getClass();
		System.out.println(objOfClass);
	}
}
public class Example 
{
	public static void main(String[] args) 
	{
		Example obj = new Example();
		Class objOfClass = obj.getClass();
		System.out.println(objOfClass);
	}
}

Output: class Create.Example

1. This method belongs to the Object class which exists in java.lang package.
2. This method returns the object of Class class. The object of the Class class represents classes and interfaces in a running Java application.
3. The returned object of the Class class is locked by static synchronized methods of the given class
4. We can’t override this method because it is final.
5. This method is written in native languages like C/C++;

What is the use of getClass() method? OR
Need of getclass() method?

1. You might hear about the Reflection in Java. If you want to perform any operation in Reflection, then this is an entry point for all reflection operations. The java.lang.Class is the starting point of Reflection.
2. If you want to know the metadata of the class at run time then you can get the information by use of getClass() method.

public class Example 
{
	int a = 0;
	String s = "Hi";
	public static void main(String[] args) throws NoSuchFieldException, SecurityException 
	{
		Example obj = new Example();
		Class objOfClass = obj.getClass();
		System.out.println("Name :"+ objOfClass.getSimpleName());
		System.out.println("Package :"+ objOfClass.getPackageName());
		System.out.println("Fields :"+ objOfClass.getFields());
	}
}

Output: Name :Example
Package :create
Fields :[Ljava.lang.reflect.Field;@6a6824be

Leave a Comment