61 lines
1.4 KiB
Java
Raw Normal View History

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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-07-07 16:23:19 -06:00
// {main: 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
*/