您的位置:首页 > 其它

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

2017-08-12 17:30 453 查看
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+ "]";
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐