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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

import java.io.*;
import java.lang.reflect.Method;
import java.util.Properties;

public class Text7 {

        /**写一个Properties格式的配置文件,用反射 的方式运行run方法
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
                // TODO Auto-generated method stub
                read();
        }
        public static void read() throws Exception{
                Properties prop = new Properties();
                File file = new File("read.properties");
                if(!file.exists())
                        try {
                                file.createNewFile();
                        } catch (IOException e) {
                                throw new RuntimeException("创建失败");
                        }
                FileInputStream fis = new FileInputStream(file);
                System.out.println("1");
               
                prop.setProperty("name","DemoClass");
                prop.load(fis);
                FileOutputStream fos = new FileOutputStream(file);
                prop.store(fos, "");
                String cls=prop.getProperty("name");
                System.out.println(cls);
                if(cls!=null){
                        System.out.println("3");
                        //Class clazz =cls.getClass();
                        System.out.println("4");
                        Method mod =cls.getClass().getMethod("run",null);
                        System.out.println("5");
                        mod.invoke(cls, null);
                        System.out.println("6");
                }
               
                       
        }
       
}
class DemoClass {
    public void run()
    {
       System.out.println("welcome to heima!");
    }   
   }

评分

参与人数 1技术分 +1 收起 理由
黄炳期 + 1

查看全部评分

2 个回复

倒序浏览
将 prop 和 file 关联
回复 使用道具 举报
注意,run()方法在DemoClass中,首先在Test中用反射的方式得到那个类的的method信息,然后才能调用,否则不可以。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马