forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLatent.java
More file actions
61 lines (56 loc) · 1.39 KB
/
Latent.java
File metadata and controls
61 lines (56 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// staticchecking/latent/Latent.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java staticchecking.latent.Latent}
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() {}
@Override
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());
}
}
/* Output:
Woof!
Click!
Mime cannot talk
*/