It appears that the designers of Java APIs made a distinction between situations when it's OK to ask for something that is missing and situations when you are supposed to ask only for things that exist.
They decided that asking for a missing key in a Map
is OK, because the content of a map is something your program controls at runtime. Therefore, designers of the class library decided that it is unreasonable to ask programmers to check if a value is present before calling Map.get
, and decided to return null
instead.
The list of methods in a class, however, remains static at all times during a particular run, so it becomes reasonable to ask programmers to call getMethod
only for methods that do exist. There are two consequences to this approach:
- You can request multiple methods without checking each one - if you have a list of methods that must exist, for example, in a plugin component, you can get their
Method
reflection objects without checking the return value of individual getMethod
calls, and
- When you do not know if a method exists, call
getMethods()
- You can still examine all methods without knowing their names by getting a full list from the Class
object.
Here is a code example to illustrate the first point. Current API lets you write this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
try {
init = cl.getMethod("init");
start = cl.getMethod("start");
stop = cl.getMethod("stop");
} catch (NoSuchMethodException ex) {
throw new PluginException("Plugin is missing a required method", ex);
}
}
...
}
instead of this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
init = cl.getMethod("init");
if (init == null) {
throw new PluginException("Plugin is missing init method");
}
start = cl.getMethod("start");
if (start == null) {
throw new PluginException("Plugin is missing start method");
}
stop = cl.getMethod("stop");
if (stop == null) {
throw new PluginException("Plugin is missing stop method");
}
}
...
}