java的潜在机制实现

潜在类型机制

含义:不关心你什么类型,你要你有对应的方法,就可以执行。但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());

      }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值