Java MCQ: Which method is used to create an instance of a class using its constructor with Java Reflection?
Answer:
Explanation:
The newInstance()
method in Java is used to create a new instance of a class using its constructor via reflection. This method is part of the Constructor
class, which is found in the java.lang.reflect
package. newInstance()
allows you to instantiate a class dynamically at runtime, even if the class name or constructor is not known at compile-time.
Here’s an example of how to use newInstance()
to create a new instance of a class:
import java.lang.reflect.Constructor;
public class CreateInstanceExample {
public static void main(String[] args) {
try {
Constructor<MyClass> constructor = MyClass.class.getConstructor(String.class);
MyClass obj = constructor.newInstance("Hello, World!");
obj.displayMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyClass {
private String message;
public MyClass(String message) {
this.message = message;
}
public void displayMessage() {
System.out.println(message);
}
}
In this example, the getConstructor()
method is used to obtain a Constructor
object representing the constructor of the MyClass
class that takes a String
argument. The newInstance()
method is then called on the constructor object to create a new instance of MyClass
, passing the string "Hello, World!"
as an argument. The new instance is then used to call the displayMessage()
method.
The newInstance()
method is a crucial part of Java Reflection, allowing developers to create objects dynamically, which is particularly useful in scenarios such as dependency injection, object serialization, and testing frameworks.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html