Method
class in Reflection API
java.lang.reflect
package.
Method
class allows you to get information about, and invoke, methods of a class dynamically at runtime.
invoke()
.
Method
class inherits the Executable
class and implements the GenericDeclaration
and Member
interfaces. Method
Class
Method
class:-
S.No | Method | Use |
---|---|---|
1 | getName() |
Returns the name of the method. |
2 | getReturnType() |
Returns the return type of the method as a Class object. |
3 | getParameterTypes() |
Returns an array of Class objects representing the parameter types. |
4 | getModifiers() |
Returns the Java language modifiers (public, private, static, etc.) as an int. |
5 | invoke(Object obj, Object... args) |
Invokes the underlying method on the given object with specified arguments. |
6 | isVarArgs() |
Checks if the method accepts a variable number of arguments. |
import java.lang.reflect.*;
class Calculator
{
public int add(int a, int b)
{
return a + b;
}
private void display(String msg)
{
System.out.println("Message: " + msg);
}
}
public class MainApp
{
public static void main(String[] args) throws Exception
{
Calculator calc = new Calculator();
Class<?> c = Calculator.class;
// Get declared methods
for (Method method : c.getDeclaredMethods())
{
System.out.println("\nMethod Name: " + method.getName());
System.out.println("Return Type: " + method.getReturnType().getSimpleName());
System.out.println("Modifiers: " + Modifier.toString(method.getModifiers()));
// Print parameter types
Class<?>[] params = method.getParameterTypes();
System.out.print("Parameter Types: ");
for (Class<?> p : params)
System.out.print(p.getSimpleName() + " ");
System.out.println();
// Access private methods
method.setAccessible(true);
// Dynamically invoke methods
if (method.getName().equals("add"))
{
Object result = method.invoke(calc, 10, 20);
System.out.println("Invoked Result: " + result);
}
else if (method.getName().equals("display"))
{
method.invoke(calc, "Hello Reflection!");
}
}
}
}
Method Name: add Return Type: int Modifiers: public Parameter Types: int int Invoked Result: 30 Method Name: display Return Type: void Modifiers: private Parameter Types: String Message: Hello Reflection!
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.