Java MCQ: Which class is used to obtain information about a class in Java Reflection?
Answer:
Explanation:
The Class
class in Java is the primary class used to obtain information about a class in Java Reflection. The Class
class is part of the java.lang
package and provides various methods to inspect the structure and behavior of classes at runtime.
To obtain a Class
object, you can use one of the following approaches:
- Using the
.class
syntax:Class<?> clazz = MyClass.class;
- Using the
getClass()
method:Class<?> clazz = obj.getClass();
- Using the
Class.forName()
method:Class<?> clazz = Class.forName("com.example.MyClass");
Once you have a Class
object, you can use it to retrieve information about the class, such as its fields, methods, constructors, and annotations. The Class
class provides methods like getDeclaredFields()
, getDeclaredMethods()
, and getDeclaredConstructors()
to inspect different components of the class.
The Class
class is fundamental to Java Reflection, as it allows you to perform a wide range of operations on classes at runtime, making it a key component of dynamic and flexible Java applications.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html