2015-09-07 11:44:36 -06:00
|
|
|
// generics/LatentReflection.java
|
2015-06-15 17:47:35 -07:00
|
|
|
// Using Reflection to produce latent typing.
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
// Does not implement Performs:
|
|
|
|
class Mime {
|
|
|
|
public void walkAgainstTheWind() {}
|
2015-11-03 12:00:44 -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"; }
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
*/
|