OnJava8-Examples/generics/LatentReflection.java

65 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/LatentReflection.java
// (c)2021 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-01-25 18:05:55 -08:00
// Using reflection for latent typing
2015-06-15 17:47:35 -07:00
import java.lang.reflect.*;
// Does not implement Performs:
class Mime {
public void walkAgainstTheWind() {}
2015-12-02 09:20:27 -08:00
public void sit() {
System.out.println("Pretending to sit");
}
2015-06-15 17:47:35 -07:00
public void pushInvisibleWalls() {}
@Override public String toString() { return "Mime"; }
2015-06-15 17:47:35 -07:00
}
// Does not implement Performs:
class SmartDog {
2015-11-03 12:00:44 -08:00
public void speak() { System.out.println("Woof!"); }
public void sit() { System.out.println("Sitting"); }
2015-06-15 17:47:35 -07:00
public void reproduce() {}
}
class CommunicateReflectively {
public static void perform(Object speaker) {
Class<?> spkr = speaker.getClass();
try {
try {
Method speak = spkr.getMethod("speak");
speak.invoke(speaker);
} catch(NoSuchMethodException e) {
2015-11-03 12:00:44 -08:00
System.out.println(speaker + " cannot speak");
2015-06-15 17:47:35 -07:00
}
try {
Method sit = spkr.getMethod("sit");
sit.invoke(speaker);
} catch(NoSuchMethodException e) {
2015-11-03 12:00:44 -08:00
System.out.println(speaker + " cannot sit");
2015-06-15 17:47:35 -07:00
}
} catch(SecurityException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
throw new RuntimeException(speaker.toString(), e);
}
}
}
public class LatentReflection {
public static void main(String[] args) {
CommunicateReflectively.perform(new SmartDog());
CommunicateReflectively.perform(new Robot());
CommunicateReflectively.perform(new Mime());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Woof!
Sitting
Click!
Clank!
Mime cannot speak
Pretending to sit
2015-09-07 11:44:36 -06:00
*/