反射机制
/面向接口编程-》解藕
反射机制(properties)(放在文件中实现)1)接口里所有方法都是抽象方法
2)接口中的变量都是常量final int i=0;方法都是public abstract void say();3)可以实现多个接口*********反射机制(properties)*******************************概述:使用反射机制之后耦合强度大大减弱,几乎变得无关,只有于meeting.properties有关只用修改meeting.properties中的value即可步骤:1)新建一个meeting.properties文件取name为talkmethod取value为javabase.TalkInAmerica2)
import java.io.IOException;import java.util.Properties;public interface TalImp { final int i=0; public abstract void say();//说话}//public class TalkInAmerica implements TalImp { public void say() { System.out.println("TALK with English"); }}/public class TalkInChina implements TalImp { public void say() { System.out.println("中国话"); }}public class Meeting { public void doMeeting(TalImp talk){ //开会 talk.say(); } public static void main(String args[]){ Meeting meeting=new Meeting(); Properties pro=new Properties(); TalImp talk; try { pro.load(Meeting.class.getResourceAsStream("meeting.properties")); } catch (IOException e) { e.printStackTrace(); } String classname=pro.getProperty("talkmethod"); try { talk=(TalImp)Class.forName(classname).newInstance(); meeting.doMeeting(talk); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }}