Java Class Class
The Class class stores the runtime state of an object or interface. An object of type Class is created automatically when a class is loaded. A Class object cannot be explicitly declared, and it is generally obtained using the getClass() method of the Object class.
Class Methods
| Method | Description |
|---|---|
static Class<?> forName(String className) |
Receives className as a parameter, loads the class, and returns the Class object corresponding to that class. |
String getName() |
Returns the class name. |
Class<? super T> getSuperclass() |
Returns the superclass. |
T newInstance() |
Creates an instance of the class contained by Class. |
Class Examples
Example 1)
package com.devkuma.tutorial.java.lang;
class Parent {
int a = 2;
int b = 3;
}
class Child extends Parent {
int c = 4;
}
public class ClassClass {
public static void main(String[] args) {
Parent p = new Parent();
Child c = new Child();
Class<?> pc = p.getClass();
Class<?> cc = c.getClass();
System.out.println("pc ClassName:" + pc.getName());
System.out.println("pc Super ClassName:" + pc.getSuperclass().getName());
System.out.println("cc ClassName:" + cc.getName());
System.out.println("cc Super ClassName:" + cc.getSuperclass().getName());
}
}
Execution result:
pc ClassName:com.devkuma.tutorial.javalang.Parent
pc Super ClassName:java.lang.Object
cc ClassName:com.devkuma.tutorial.javalang.Child
cc Super ClassName:com.devkuma.tutorial.javalang.Parent
In the example, you can see that the class name and superclass name are displayed on the screen.
Example 2)
package com.devkuma.tutorial.javalang;
class Calc {
int a = 2;
int b = 3;
public int sum() {
return a + b;
}
}
public class ClassClass2 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazz = Class.forName("com.devkuma.tutorial.javalang.Calc");
Calc calc = (Calc) clazz.newInstance();
System.out.println("sum : " + calc.sum());
}
}
Execution result:
sum : 5
So far, objects have been created using new. The example above creates an object using Class.forName and the newInstance() method without using new. This means the class is loaded not when normal class loading occurs, but when Class.forName() is executed. This is called runtime dynamic loading. This approach can have security or quality issues, so except for special cases such as JDBC loading, creating classes this way should be avoided.