2015-09-07 11:44:36 -06:00
|
|
|
// staticchecking/latent/Latent.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-07-28 12:48:23 -06:00
|
|
|
// {java staticchecking.latent.Latent}
|
2015-06-15 17:47:35 -07:00
|
|
|
package staticchecking.latent;
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
class Dog {
|
|
|
|
public void talk() {
|
|
|
|
System.out.println("Woof!");
|
|
|
|
}
|
|
|
|
public void reproduce() {}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Robot {
|
|
|
|
public void talk() {
|
|
|
|
System.out.println("Click!");
|
|
|
|
}
|
|
|
|
public void oilChange() {}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Mime {
|
|
|
|
public void walkAgainstTheWind() {}
|
|
|
|
public String toString() { return "Mime"; }
|
|
|
|
}
|
|
|
|
|
|
|
|
class Communicate {
|
|
|
|
public static void speak(Object speaker) {
|
|
|
|
try {
|
|
|
|
Class<? extends Object> spkr =
|
|
|
|
speaker.getClass();
|
|
|
|
Method talk =
|
|
|
|
spkr.getMethod("talk", (Class[])null);
|
|
|
|
talk.invoke(speaker, new Object[]{});
|
|
|
|
} catch(NoSuchMethodException e) {
|
|
|
|
System.out.println(
|
|
|
|
speaker + " cannot talk");
|
|
|
|
} catch(IllegalAccessException e) {
|
|
|
|
System.out.println(
|
|
|
|
speaker + " IllegalAccessException");
|
|
|
|
} catch(InvocationTargetException e) {
|
|
|
|
System.out.println(
|
|
|
|
speaker + " InvocationTargetException");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class Latent {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Communicate.speak(new Dog());
|
|
|
|
Communicate.speak(new Robot());
|
|
|
|
Communicate.speak(new Mime());
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Woof!
|
|
|
|
Click!
|
|
|
|
Mime cannot talk
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|