Java MCQ: Which method is used to invoke a method on an object using Java Reflection?
Answer:
Explanation:
The invoke()
method in Java is used to invoke a method on an object using reflection. This method is part of the Method
class, which is found in the java.lang.reflect
package. The invoke()
method allows you to dynamically call a method on an instance of a class, even if the method’s name or parameters are not known until runtime.
Here’s an example of how to use the invoke()
method:
import java.lang.reflect.Method;
public class InvokeMethodExample {
public static void main(String[] args) {
try {
MyClass obj = new MyClass();
Method method = MyClass.class.getDeclaredMethod("myMethod", String.class);
method.invoke(obj, "Hello, World!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyClass {
public void myMethod(String message) {
System.out.println(message);
}
}
In this example, the getDeclaredMethod()
method is used to obtain a Method
object representing the myMethod
method of the MyClass
class. The invoke()
method is then used to call myMethod
on an instance of MyClass
, passing the string "Hello, World!"
as an argument.
The invoke()
method is highly versatile and can be used to call methods with different parameter types and return values. However, it is important to handle exceptions such as IllegalAccessException
, IllegalArgumentException
, and InvocationTargetException
that may be thrown when invoking a method reflectively.
Reflection-based method invocation is a powerful tool for building dynamic and flexible applications, but it should be used with caution due to potential performance overhead and security risks.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html