160. Getting static methods

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

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

public void weighsIn() {}

public static void cultivate(Seed seeds) {
System.out.println("The cultivate() method was invoked ...");
}

public static void peel(Slice slice) {
System.out.println("The peel() method was invoked ...");
}

// getters, setters, toString() omitted for brevity
}

This class has two static methods—cultivate() and peel(). Let's fetch these two methods in List<Method>.

The solution to this problem has two main steps:

  1. Fetch all the available methods of the given class
  2. Filter those that contain the static modifier via the Modifier.isStatic() method

In code, it looks like this:

List<Method> staticMethods = new ArrayList<>();

Class<Melon> clazz = Melon.class;
Method[] methods = clazz.getDeclaredMethods();

for (Method method: methods) {

if (Modifier.isStatic(method.getModifiers())) {
staticMethods.add(method);
}
}

The result of printing the list via System.out.println() is as follows:

[public static void 
modern.challenge.Melon.peel(modern.challenge.Slice),

public static void
modern.challenge.Melon.cultivate(modern.challenge.Seed)]

One step further, and we may want to call one of these two methods.

For example, let's call the peel() method (notice that we pass null instead of an instance of Melon since a static method doesn't need an instance):

Method method = clazz.getMethod("peel", Slice.class);
method.invoke(null, new Slice());

The output signals that the peel() method was successfully invoked:

The peel() method was invoked ...
..................Content has been hidden....................

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