黑马程序员技术交流社区

标题: 跪求帮忙! [打印本页]

作者: 敗唫①輩ふ    时间: 2013-11-6 20:36
标题: 跪求帮忙!
本帖最后由 敗唫①輩ふ 于 2013-11-6 20:38 编辑

已知一个类,定义如下:
   package cn.itcast.heima;
      public class DemoClass {
      public void run()
      {
         System.out.println("welcome to heima!");
      }   
     }
(1) 写一个Properties格式的配置文件,配置类的完整名称。
(2) 写一个程序,读取这个Properties配置文件,获得类的完整名称并加载这个类,用反射 的方式运行run方法。


我敲完代码后发现有地方不对,请哪位大神指教,感激不尽{:soso_e149:}


public class Test8 {
        /**
         * 获取输入流,用于读取配置文件信息
         * @param filePath 配置文件路径
         * @return 返回指定配置文件的输入流
         */
        public static InputStream getInputStream(String filePath) {
                InputStream ips = null;
                //通过getResourceAsStream方法获取输入流
                ips = Test8.class.getResourceAsStream(filePath);
                return ips;
        }
       
        /**
         * 反射调用方法
         * @param filePath 配置文件路径
         * @throws Exception 为了演示功能没有对异常进行针对性处理
         */
        public static void reflectInovokeMethod(String filePath) throws Exception{
                Properties properties = new Properties();
                InputStream ips = getInputStream(filePath);
                properties.load(ips);
               
                String className = properties.getProperty("className");
                Class clazz = Class.forName(className);
                Object obj = clazz.newInstance();
                Method methodRun = clazz.getMethod("run", null);
                methodRun.invoke(obj, null);
               
        }
       
        /**
         * 主函数进行功能测试
         */
        public static void main(String[] args) throws Exception{
                //配置文件路径
                String filePath = "resources\\config.properties";
               
                //通过反射调用run方法
                reflectInovokeMethod(filePath);
        }

}


作者: 零下五度的水    时间: 2013-11-6 21:15
public static InputStream getInputStream(String filePath) {
   ............................
   ips = Test8.class.getResourceAsStream(filePath);
}
getResourceAsStream 代码你没给,目测是这行出问题了
Test8.class。。。 这个语法调用的是 Class 类的方法吧




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2