Are you confused about what Class Class In Java is? Don’t worry we are here to help you.
Reading this article will help you to get a clear insight into what class class in Java is, clearing all your doubts and helping you in your journey of becoming an Android Developer.
What Class Class In Java Is?
Class Class in Java is present in Java.lang package, mainly used for building Application User Interfaces (APIs) and many Java Applications.
java.lang.Class is among one of the most important classes in Java which offers several important methods used in Application development, these methods are commonly used for loading Oracle or MySQL drivers in Java applications.
Apart from all this, Java.lang.Class also provides methods like Class.newInstance() which is helpful in creating an instance of a class without using the new() operator, unlike other classes. The Class Class present in Java contains a private constructor, this is why creating an instance is not possible with the new keyword, So for creating a new object class we basically use three methods, we will be discussing these three methods below for your better understanding. The object of Class Class in Java is also used to represent various classes, enum, interfaces, and annotations in Java applications.
Three Ways To Create A Class Class In Java
As we have also discussed above, java contains a private constructor which makes it impossible to create an instance with a new keyword so for creating a new object class we basically use three methods, these three methods include-
- Using class.forName().
- Using getClass().
- Using Myclass.class().
Now, We will discuss each one of the methods in detail, for your better clarity and understanding.
-
Using class.forName()
This method is used in Java for dynamically loading and initializing classes at runtime. class.forName is particularly useful in scenarios where you are not aware of the class name until runtime or when you want to load a class based on user input.
The common example of using class.forName() in Java is given below for your reference.
public class Main {
public static void main(String[] args) {
tryÂ
{
   Class<?> myClass = Class.forName(“MyClass”);
System.out.println(“Loaded Class: ” + myClass.getName());
  } catch (ClassNotFoundException e) {
  System.out.println(“Class not found: ” + e.getMessage());
        }
    }
}
In the example above, We use Class.forName(“MyClass”) to dynamically load the class named “MyClass”.
If the class is found and loaded successfully, we will print its name using myClass.getName().
-
Using get.Class()
The getClass() method in Java is used to obtain the runtime class of an object. It is a method defined in the Object class, which is the root class for all Java classes.
Let us understand the implementation of get.class() with the help of simple code:
public class Main {
public static void main(String[] args)Â
{
   String str = “Hello, World!”;
   Class<?> strClass = str.getClass();
System.out.println(“Runtime Class: ” + strClass.getName());
    }
}
-
Using Myclass.class
Myclass.class is commonly used when the given class is already known before creating an object. This method is used for both primitive as well as for non-primitive data types.Â
The .class function after the class name helps in referencing the class object which is used to represent the given class.
Below is the code for your better understanding of this method:
Class<?> fruitClass;
 switch (fruitName.toLowerCase()) {
case “apple”:
         fruitClass = Apple.class;
  break;Â
case “banana”:
    fruitClass = Banana.class;
  break;
   case “orange”:
       fruitClass = Orange.class;
    break; Â
    return;
        }
try {
            Fruit fruit = (Fruit) fruitClass.getDeclaredConstructor().newInstance();
            fruit.displayInfo();     Â
        }
    }
}
interface Fruit {
    void displayInfo();
}
class Apple implements Fruit {
    public void displayInfo() {
        System.out.println(“This is an apple.”);
    }
}
class Banana implements Fruit {
    public void displayInfo() {
        System.out.println(“This is a banana.”);
    }
}
class Orange implements Fruit {
    public void displayInfo() {
        System.out.println(“This is an orange.”);
    }
}
In this code above, The user will give input of their favorite fruit.
Based on the user’s input, the program uses MyClass.class method (e.g., Apple.class, Banana.class, or Orange.class) to dynamically create an instance of the selected fruit class. These selected fruit object then displays information about themselves.
Methods Of Class Class In Java
Still Confused about what are the methods used for Class Class in Java? Don’t worry, below is the table made for your reference which includes some most commonly used methods and their uses in Java.lang.class.
Reading this table thoroughly will help you to get clarity about the different types of methods used in Java.lang.class.
S.NO. | Methods | Why is it used |
1 | asSubclass(Class < U> clazz) | This method is used in Java to safely cast a class reference to a subclass reference at runtime, It mainly ensures that the casting is done safely. |
2 | getName() | This method is used for Returning the fully qualified name of the class. |
3 | getSimpleName() | This method is used to return the simple name of the class that is without the package name. |
4 | isInterface() | This method in Java is basically used for checking if the class is an interface or not. |
5 | isArray() | It is used for checking if the class represents an array type or not. |
6 | isPrimitive() | This method in Java is used to check if the class represents a primitive type or not. |
7 | getPackage() | This method is used to return the package of the class. |
8 | getSuperclass() | getSuperclass() method in Java is used to return the superclass of the class. |
9 | getInterfaces() | This method in Java.lang.class returns an array of interfaces that are implemented by the class. |
10 | getDeclaredFields() | This method in Java.lang.class is used to return an array of fields declared by the class. |
11 | getDeclaredAnnotation(Class < A> annClass) | This method is used to return the present element’s annotation if it is present, else this method returns a null value. |
12 | isAssignableFrom(Class<?> cls) | It is used to check if the class represented by the object can be assigned from the specified class. |
13 | getAnnotation(Class<A> annotationClass):Â | This method in Java Class Class is used to return the annotation associated with the class, if present. |
14 | getComponentType() | This method of Java Class Class is used to return the class that represents the component type of an array.
If there is no component present it will declare null value. |
Learn Java With PW Skills
Want to become a Java Developer but don’t know where to start from?? Don’t worry we are here for you!
Enroll in our comprehensive Java with DSA course to master the art of programming.
This 4 month’s Course will provide you an expert mentorship with Top Programmers, working on core projects with experts, and learning new technologies of today’s world.
If you are a beginner looking forward to building your career as a Java developer then this course is surely for you. This course also offers soft skill training which will help you in preparing yourself for future job interviews.
Class Class In Java FAQs
What is the Class class in Java?
The Class class in Java is a built-in class that allows us to define a class within another class. It basically provides methods for inspecting and working with class metadata at runtime.
What are some common methods provided by the Class class in Java?
Some common methods provided by the Class class in Java include getName(), getSimpleName(), isInterface(), isArray(), isPrimitive(), getPackage(), getSuperclass(), getInterfaces(), getDeclaredFields(), etc. you can refer the table above to see the usage of these methods.
What can I build using Class Class in Java?
The class class in Java is a feature that allows us to define a class within a class. This feature is widely used by developers to make flexible and reliable software systems as this feature allows dynamic class loading, metadata processing, and much more.