OnJava8-Examples/generics/LatentReflection.java

62 lines
1.6 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/LatentReflection.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Using Reflection to produce latent typing.
import java.lang.reflect.*;
import static net.mindview.util.Print.*;
// Does not implement Performs:
class Mime {
public void walkAgainstTheWind() {}
public void sit() { print("Pretending to sit"); }
public void pushInvisibleWalls() {}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public String toString() { return "Mime"; }
}
// Does not implement Performs:
class SmartDog {
public void speak() { print("Woof!"); }
public void sit() { print("Sitting"); }
public void reproduce() {}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
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) {
print(speaker + " cannot speak");
}
try {
Method sit = spkr.getMethod("sit");
sit.invoke(speaker);
} catch(NoSuchMethodException e) {
print(speaker + " cannot sit");
}
2015-05-06 12:09:38 -07:00
} catch(SecurityException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
2015-04-20 15:36:01 -07:00
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());
}
} /* Output:
Woof!
Sitting
Click!
Clank!
Mime cannot speak
Pretending to sit
*///:~