java 对缺乏潜在类型机制的补偿 :反射

来源:互联网 发布:python中的迭代器 编辑:程序博客网 时间:2024/04/29 15:33
package lu.generics;import static lu.utils.Print.*;import java.lang.reflect.Method;/* * 通过反射,CommunicateReflectively.perform()能够动态地确定所需要的方法是否可用并调用他们。 * 他甚至能够处理Mime只有一个必须的方法这一事实,并能够部分实现其目标。 * 反射将所有的类型检查都转移到了运行时,因此在许多情况下并不是我们所希望的。*/class Mime{public void walkAgainstTheWind(){}public void sit(){print("Pretending to sit");}public void pushInvisibleWalls(){}public String toString(){return "Mine";}}class SmartDog{public void speak(){print("Woof!");}public void sit(){print("Sitting");}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){print(speaker+" cannot speak");}try{Method sit=spkr.getMethod("sit");sit.invoke(speaker);}catch(NoSuchMethodException e){print(speaker+" cannot sit");}}catch(Exception 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());   }}


0 0