A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

1.Java框架(frame)

/*
通俗例子:
我做房子(框架)卖给用户住,由用户自己安装门窗和空调(用户自定义类/用户自定义其它信息)
用户需要使用我的房子(框架),把符合框架中结构的门窗插入进我提供的框架中.
框架与工具类区别:
框架调用用户提供的类
工具类被用户的类调用
示例:
         利用反射运行指定的某个类中的main方法,
         通过arg[0]来接收要运行的类名,也就是说
         我已写好这个功能,而你要运行的类还不存在
        我这个功能可以提前编译,你只需在运行时提供给我要运行的类即可.
框架要解决的核心问题:
     我若干年前写的程序调用你若干年后写的程序->反射机制
为什么要用框架?
    框架相当于半成品->也就是说提高开发效率
*/
模拟框架:利用反射机制读取配置文件

public class FrameMN {
public static  String loadProp()throws IOException{   
   
  Properties property=new Properties();
  
  BufferedInputStream bis=null;
  InputStream is=null;
  try{
  /* bis=new BufferedInputStream
           (new FileInputStream("config.properties"));//这里的根目录为工程名称(JavaEnhance)
                                                     //"config.properties"相当于".\\config.properties"
*/   

    System.out.println(System.getProperty("java.class.path"));//classpath路径  

   /*   
   bis=new BufferedInputStream(FrameMN.class.getClassLoader().getResourceAsStream
                              ("com/itheima/day2/config.properties"));//将会在classpath+指定的路径(com/itheima/day2/config.properties)
                                                                     //下查找,com前面不能有/->将不再是相对路径
   */     
bis=new BufferedInputStream(FrameMN.class.getResourceAsStream("/com/itheima/day2/config.properties"));
  
  property.load(bis);   
  return property.getProperty("className");
   }
  finally{
    if(bis!=null)
      bis.close();
  }
}

public static void main(String[] args)throws Exception{
      String className=loadProp();
      Collection collections=(Collection)Class.forName(className).newInstance();
      collections.add("3");
      collections.add(2);
      System.out.println(collections);//[3, 2]
      System.out.println(System.getProperty("user.dir"));
   }
}
目录结构:



注意几点:

/*
config.properties 该如何配置其位置?
1.相对路径
   其实就是System.getProperty("user.dir");
   相对路径随时有可能在变,但是可以通过 System.getProperty("user.dir")来获取当前程序执行所在的相对路径.
  但是如果这个文件不再当前路径下->找不到引发IO异常
2.绝对路径
  从盘符开始路径:d:\abc\1.txt
  不建议使用这样做缺点:用户没有d:盘符呢?
解决办法:
例如:把某个软件安装到某个目录->通过方法获取到其安装路径->在与内部的配置文件拼接形成绝对路径
一个错误:
  Frame.class.getClass()
*/

1 个回复

倒序浏览
孤独成瘾 来自手机 中级黑马 2016-1-3 23:06:59
沙发
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马