现在的位置: 首页 > 综合 > 正文

用反射实现潜在类型机制

2013年12月02日 ⁄ 综合 ⁄ 共 1303字 ⁄ 字号 评论关闭
  1. package com.poson.sweetop.generics;
  2. import java.lang.reflect.Method;
  3. class Mime {
  4.     public void sit() {
  5.         System.out.println("Mime sit");
  6.     }
  7.     public void speak() {
  8.         System.out.println("Mime speak");
  9.     }
  10.     
  11.     public String toString(){
  12.         return "Mime";
  13.     }
  14. }
  15. class Robot {
  16.     public void speak() {
  17.         System.out.println("Robot speak");
  18.     }
  19.     
  20.     public String toString(){
  21.         return "Robot";
  22.     }
  23. }
  24. class CommunicateReflectively {
  25.     public static void perform(Object object) {
  26.         Class<?> oc = object.getClass();
  27.         try {
  28.             try {
  29.                 Method speak = oc.getMethod("speak");
  30.                 speak.invoke(object);
  31.             } catch (NoSuchMethodException e) {
  32.                 System.out.println(object + " can't speak");
  33.             }
  34.             try {
  35.                 Method sit = oc.getMethod("sit");
  36.                 sit.invoke(object);
  37.             } catch (NoSuchMethodException e) {
  38.                 System.out.println(object + " can't sit");
  39.             }
  40.         } catch (Exception e) {
  41.             e.printStackTrace();
  42.         }
  43.     }
  44. }
  45. public class LatenReflection {
  46.     public static void main(String[] args) {
  47.         CommunicateReflectively.perform(new Robot());
  48.         CommunicateReflectively.perform(new Mime());
  49.     }
  50. }

如果他走起来像鸭子,叫起来也像鸭子,那么可以把他当鸭子。

不用被强制实现接口。

抱歉!评论已关闭.