How to use Java reflection to obtain a class object?
There are several common methods for obtaining a Class object using Java reflection.
- Loading a class in Java.
Class<?> clazz = Class.forName("com.example.MyClass");
- This is a class.
Class<?> clazz = MyClass.class;
- What is the class of this object?
MyClass obj = new MyClass();
Class<?> clazz = obj.getClass();
Please note that the Class objects obtained from the three methods above are of generic type Class>, representing an unknown class type. If you know the specific type of the class, you can use that specific type instead of > to obtain the Class object. For example:
Class<MyClass> clazz = MyClass.class;
In conclusion, the basic steps to obtain a Class object using Java reflection are: determine the fully qualified name of the class or obtain a reference to the known class -> use the appropriate method to acquire the Class object.