Java Reference
In-Depth Information
if (walkMethod != null) {
try {
// Invoke the walk() method
walkMethod.invoke(list[i]);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static Method getWalkMethod(Object obj) {
Class c = obj.getClass();
Method walkMethod = null;
try {
walkMethod = c.getMethod("walk");
return walkMethod;
}
catch (NoSuchMethodException e) {
// walk() method does not exist
}
return null;
}
}
The getWalkMethod() method looks for a walk() method in the specified object's class. If it finds a walk()
method, it returns the reference of the found method. Otherwise, it returns null . You have changed the parameter
type of the letThemWalk() method from an array of Person to an array of Object . You can use the following snippet of
code to test the modified Walkables class:
Object[] objects = new Object[4];
objects[0] = new Person("Jack");
objects[1] = new Duck("Jeff");
objects[2] = new Person("John");
objects[3] = new Object(); // Does not have a walk() method
// Let everyone walk
Walkables.letThemWalk(objects);
Jack (a person) is walking.
Jeff (a duck) is walking.
John (a person) is walking.
The output shows that your solution works. It lets persons and ducks walk together. At the same time, it does
not force an object to walk if that object does not know how to walk. You passed four objects to the letThemWalk()
method and no attempt was made to invoke the walk() method on the fourth element of the array because the Object
class does not have a walk() method.
 
Search WWH ::




Custom Search