潛在類型機制
含義:不關心你什麼類型,你要你有對應的方法,就可以執行。但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());
}
}