您的位置:首页 > 编程语言 > Java开发

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

2016-05-02 14:36 316 查看
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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: