潜在类型机制
含义:不关心你什么类型,你要你有对应的方法,就可以执行。但java没有这种机制,只能用interface技术实现:
//接口
public interface Performs
{
voidspeak();
voidsit();
}
//接口实现
class PerformingDog implements Performs
{
publicvoid speak(){System.out.println("Click");}
publicvoid sit(){System.out.println("Sitting");}
publicvoid reproduce(){}
}
class Communicate
{
publicstatic <T extends Performs> void perform(T performer){
performer.speak();
performer.sit();
}
}
class Dos
{
publicstatic void main(String[] args){
PerformingDogd=new PerformingDog();
Communicate.perform(d);
}
}
潜在机制的补偿
采用接口的方式其实两个类还是有些关系的,都共同实现同一个接口,但是如何实现两类一点关系都没有的潜在机制呢?
采用反射机制可以有效实现潜在机制(不关心类型,注重方法)
import java.lang.reflect.*;
//类一:Mine类
class Mine
{
public void walkAganinstTheWind(){}
public voidsit(){System.out.println("Pretending to sit");}
public void pushInvisobleWalls(){};
public String toString(){return"Mine";};
}
//类二:SmartDog类
class SmartDog
{
public void speak(){System.out.println("Wooof");}
public voidsit(){System.out.println("Sitting");}
public void reproduce(){}
}
//反射:用speaker(Object)来接受一个对象,
classCommunicateReflectively
{
public static void perform(Objectspeaker){
Class<?> spkr=speaker.getClass();//得到类型信息
try{
try{
Method speak=spkr.getMethod("speak");//得到该类的方法
speak.invoke(speaker);//调用,此处invoke()是Method类的一个方法
}catch(NoSuchMethodException e){
System.out.println(speaker+" can't sit");
}
}catch(Exception e){
throw new RuntimeException(speaker.toString(),e);
}
}
}
public classLatentReflecttion
{
public static void main(String[] args){
CommunicateReflectively.perform(new Mine());
CommunicateReflectively.perform(newSmartDog());
}
}