159. Invoking an instance method

Let's assume that we have the following Melon class:

public class Melon {
...
public Melon() {}

public List<Melon> cultivate(
String type, Seed seed, int noOfSeeds) {

System.out.println("The cultivate() method was invoked ...");

return Collections.nCopies(noOfSeeds, new Melon("Gac", 5));
}
...
}

Our goal is to invoke the cultivate() method and obtain the return via the Java Reflection API.

First, let's fetch the cultivate() method as a Method via Method.getDeclaredMethod(). All we have to do is pass the name of the method (in this case, cultivate()) and the right types of parameters (StringSeed, and intto getDeclaredMethod(). Second argument of getDeclaredMethod() is a varargs of Class<?> type, therefore, it can be empty for methods with no parameters or contain the list of parameters types as in the following example:

Method cultivateMethod = Melon.class.getDeclaredMethod(
"cultivate", String.class, Seed.class, int.class);

Then, let's obtain an instance of the Melon class. We want to invoke an instance method; therefore, we need an instance. Relying on the empty constructor of Melon and the Java Reflection API, we can do it as follows:

Melon instanceMelon = Melon.class
.getDeclaredConstructor().newInstance();

Finally, we focus on the Method.invoke() method. Mainly, we need to pass to this method the instance used for calling the cultivate() method and some values for the parameters:

List<Melon> cultivatedMelons = (List<Melon>) cultivateMethod.invoke(
instanceMelon, "Gac", new Seed(), 10);

The success of invocation is revealed by the following message:

The cultivate() method was invoked ...

Moreover, if we print the return of invocation via System.out.println(), then we get the following result:

[Gac(5g), Gac(5g), Gac(5g), ...]

We've just cultivated 10 gacs via reflection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.67.5