Parameters
The `getMethod()` function accepts two parameters:
1. `String name`
- This parameter represents the name of the method you want to retrieve.
- It should be provided as a String value.
- The method name is case-sensitive, so make sure to provide the exact name of the method.
- If the method is overloaded (i.e., multiple methods with the same name but different parameter types), you need to specify the parameter types to distinguish between them.
2. `Class<?>... parameterTypes`
- This parameter is a variable-length argument (varargs) that allows you to specify the types of the method's parameters.
- It is an array of `Class` objects, where each object represents the type of a parameter.
- If the method has no parameters, you can either pass an empty array `(new Class[0])` or omit this parameter entirely.
- For methods with parameters, you must provide the `Class` objects corresponding to each parameter type in the correct order.
- Primitive types should be specified using their corresponding wrapper classes (e.g., `int.class` for an int parameter).
For example :
Class<MyClass> myClass = MyClass.class;
Method method = myClass.getMethod("myMethod", String.class, int.class);
In this example, we're retrieving a method named `"myMethod"` from the `MyClass` class. The method takes two parameters: a String and an int. We provide the `String.class` and `int.class` as the parameter types to specify the expected types.
Return Value
The `getMethod()` function returns a `Method` object that represents the method you want to retrieve. The `Method` class provides various methods to obtain information about the method & invoke it.
Let’s see some commonly used methods of the `Method` class:
- `getName()`: Returns the name of the method as a String.
- `getReturnType()`: Returns the `Class` object representing the return type of the method.
- `getParameterTypes()`: Returns an array of `Class` objects representing the types of the method's parameters.
- `getModifiers()`: Returns an integer value representing the modifiers of the method (e.g., public, private, static).
- `invoke(Object obj, Object... args)`: Invokes the method on the specified object with the provided arguments.
For example :
Class<MyClass> myClass = MyClass.class;
Method method = myClass.getMethod("myMethod", String.class, int.class);
String methodName = method.getName();
Class<?> returnType = method.getReturnType();
Class<?>[] parameterTypes = method.getParameterTypes();
MyClass obj = new MyClass();
Object result = method.invoke(obj, "Hello", 42);
In this example, we retrieve the method named `"myMethod"` from the `MyClass` class. We then use the `Method` object to obtain the method name, return type, and parameter types. Finally, we create an instance of `MyClass` and invoke the method on that instance using the `invoke()` method, passing the necessary arguments.
Note: The `invoke()` method returns an `Object` that represents the result of the method invocation. You can cast it to the appropriate type based on the method's return type.
Exceptions
The `getMethod()` function throws two types of exceptions:
1. `NoSuchMethodException`:
- This exception is thrown when the specified method is not found in the class or any of its superclasses.
- It indicates that the method with the given name & parameter types does not exist.
- If you try to retrieve a method that is not defined in the class, or if you provide incorrect method name or parameter types, a `NoSuchMethodException` will be thrown.
2. `SecurityException`:
- This exception is thrown when there is a security restriction preventing access to the method.
- It occurs when the current security manager denies access to the method.
- This exception is related to the Java security model & is thrown when the code does not have sufficient permissions to access the method.
To handle these exceptions, you can use a try-catch block or declare them in the method signature using the `throws` keyword.
Let’s see an example of handling the exceptions:
try {
Class<MyClass> myClass = MyClass.class;
Method method = myClass.getMethod("myMethod", String.class, int.class);
// Use the retrieved method
} catch (NoSuchMethodException e) {
// Handle the case when the method is not found
e.printStackTrace();
} catch (SecurityException e) {
// Handle the case when there is a security restriction
e.printStackTrace();
}
In this example, we wrap the `getMethod()` call inside a try block. If a `NoSuchMethodException` is thrown, indicating that the method is not found, we catch it in the corresponding catch block & handle it appropriately (e.g., print the stack trace or log an error message).
Similarly, if a `SecurityException` is thrown due to a security restriction, we catch it in the respective catch block & handle it accordingly.
Examples
Now, let's understand some practical examples of using the `getMethod()` function in different scenarios:
1. Getting Method of a Class
Suppose we have a class named `MyClass` with a method `myMethod` that takes a String parameter & returns an int. Let’s look at an example of how to retrieve & invoke this method using `getMethod()`:
public class MyClass {
public int myMethod(String str) {
return str.length();
}
}
// Usage
Class<MyClass> myClass = MyClass.class;
try {
Method method = myClass.getMethod("myMethod", String.class);
MyClass obj = new MyClass();
int result = (int) method.invoke(obj, "Hello");
System.out.println("Result: " + result);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
In this example, we define the `MyClass` with the `myMethod` method. We use `getMethod()` to retrieve the method by providing its name and parameter type. Then, we create an instance of `MyClass`, invoke the method on that instance using `invoke()`, and print the result.
Output:
Result: 5
The `myMethod` method returns the length of the input String, which is 5 for the String "Hello".
2. Getting Method of an ArrayList
Let's say we want to retrieve the `add` method of the `ArrayList` class, which adds an element to the list.
For example:
import java.util.ArrayList;
// Usage
Class<ArrayList> arrayListClass = ArrayList.class;
try {
Method addMethod = arrayListClass.getMethod("add", Object.class);
ArrayList<String> list = new ArrayList<>();
addMethod.invoke(list, "Apple");
addMethod.invoke(list, "Banana");
System.out.println("ArrayList: " + list);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
In this example, we retrieve the `add` method of the `ArrayList` class using `getMethod()`. We provide the method name `add' and the parameter type `Object.class`, as the `add` method accepts an object of any type.
We create an instance of `ArrayList<String>` & invoke the `add` method on it using `invoke()`, passing the elements we want to add. Finally, we print the modified ArrayList.
Output:
ArrayList: [Apple, Banana]
The `add` method is successfully invoked, and the elements "Apple" and "Banana" are added to the ArrayList.
3. Getting Method of a Thread
In this example, we'll retrieve the `start` method of the `Thread` class, which starts the execution of a thread.
For example :
// Usage
Class<Thread> threadClass = Thread.class;
try {
Method startMethod = threadClass.getMethod("start");
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
startMethod.invoke(thread);
thread.join();
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
In this example, we retrieve the `start` method of the `Thread` class using `getMethod()`. We provide the method name `"start"` without any parameter types, as the `start` method doesn't accept any arguments.
We create an instance of `Thread` using a lambda expression that defines the code to be executed in the thread. Then, we invoke the `start` method on the thread instance using `invoke()`.
After starting the thread, we call the `join()` method to wait for the thread to complete its execution. This ensures that the main thread waits for the child thread to finish before proceeding.
Output:
Thread is running
The `start` method is invoked on the thread, and the code inside the lambda expression is executed, printing the message "Thread is running."
Frequently Asked Questions
Can `getMethod()` retrieve private methods of a class?
No, `getMethod()` can only retrieve public methods. To access private methods, you can use `getDeclaredMethod()` instead.
What happens if the method is not found using `getMethod()`?
If the method is not found, a `NoSuchMethodException` is thrown, indicating that the specified method does not exist in the class.
Can `getMethod()` retrieve methods from superclasses?
Yes, `getMethod()` searches for the specified method in the class & its superclasses. If the method is inherited from a superclass, it will be retrieved.
Conclusion
In this article, we learned about the `getMethod()` function in Java, which allows us to retrieve class methods dynamically at runtime. We discussed its syntax, parameters, return value, and exceptions. With practical examples, we saw how `getMethod()` can be used to retrieve methods from a class, an ArrayList, and a Thread.
You can also check out our other blogs on Code360.