使用反射机制完成学生对象的创建并输出学生信息。

来源:互联网 发布:佳能ip1180清零软件 编辑:程序博客网 时间:2024/05/20 16:12
publicclass TestStudent {public static void main(String[] args)throws Exception, Exception {        Scanner sc=new Scanner(System.in);        System.out.println("请输入学生的信息(姓名:年龄:成绩):");        String s=sc.nextLine();        //用冒号分隔开        String[] ss = s.split(":");        //存放分隔后的数据        Properties p=new Properties();        File f=newFile("student.properties");        if(!f.exists()){            p.load(new FileInputStream(f));        }        //设置p的属性name值为ss[0]        p.setProperty("name", ss[0]);        //设置p的属性age值为ss[1]        p.setProperty("age", ss[1]);        //设置p的属性score值为ss[2]        p.setProperty("score", ss[2]);        //把得到的p的值存储到刷新后的.properties文件里        p.store(new FileOutputStream(f),"student.properties");        //找到需要反射的类放到定义的Class中        Class<?>c=Class.forName("com.sxt.Test25.Student");        //找到刚刚反射到的类的构造方法的参数以及类型        Constructor<?>cc=c.getDeclaredConstructor(String.class,int.class,float.class);        //定义一个学生类把反射到的构造方法参数放到学生类中        Student ns=(Student)cc.newInstance(p.getProperty("name"),Integer.parseInt(p.getProperty("age")),Float.parseFloat(p.getProperty("score")));        //调用反射到的类的方法        Methodm=c.getDeclaredMethod("toString", null);        //输出调用的方法并吧存放在学生类中的数据放进去        System.out.println(m.invoke(ns, null));    }}publicclass Student {String name;    int age;    float score;    public Student() {}    public Student(String name, int age, floatscore) {        this.name = name;        this.age = age;        this.score = score;    }    @Override    public String toString() {        return "Student [name=" + name+ ", age=" + age + ", score=" + score+ "]";
}}


 

阅读全文
0 0
原创粉丝点击