本帖最后由 冯华亮 于 2012-8-10 22:30 编辑
看完张老师视频后,动手实践了一下反射机制的运用。看视频的时候感觉反射简单,结果一动手的时候就出现了各种各样的错误,建议大家在看视频的时候还是要多做练习,看的懂是一回事,会写又是另一回事!分享交流一下学习经验。下面是代码:- import java.lang.reflect.*;
- class Student
- {
- public String name;
- private int age;
- private int score;
- public Student(){}
- public Student(String str){
- this.name=str;
- }
- public Student(String name,int age,int score){
- this.name=name;
- this.age=age;
- this.score=score;
- }
- public String getname(){
- return this.name;
- }
- public int getage()
- {
- return this.age;
- }
- public int getscore()
- {
- return this.score;
- }
- public void printInfo(){
- System.out.println("该生的信息如下:"+"\r\n"+name+" "+age+" "+score);
- }
- public String toString(){
- if(this.age==0&&this.score==0)
- {
- return "毕加猪经典语录:"+"\r\n"+name;
- }
- return "毕加猪经典语录:"+"\r\n"+name+" "+age+" "+score;
- }
- }
- class ReflectDemo
- {
- public static void main(String[] args) throws Exception
- {
- Student stu1=new Student("黑马_冯华亮",11,22);
- Student stu2=new Student("黑马_郑小杰",33,44);
- getconstructor();
-
- System.out.println("----------------------------");
- getfield(stu1);
-
- System.out.println("----------------------------");
- getmethod(stu2);
- }
- public static void getconstructor() throws Exception
- {
- Constructor constru=Class.forName("Student").getConstructor(String.class);
- Student stu=(Student)constru.newInstance("笑只是个表情,与快乐无关");
- System.out.println(stu.toString());
- }
- public static void getfield(Student stu) throws Exception
- {
- //Student类中score是private的,采用getDeclaredField() 方法
- Field field=Class.forName("Student").getDeclaredField("score");
- field.setAccessible(true);
- int score=(int)field.get(stu);
- System.out.println(stu.getname()+"的成绩是: "+score);
- }
- public static void getmethod(Student stu) throws Exception
- {
- Method mthod=Class.forName("Student").getMethod("printInfo");
- mthod.invoke(stu);
- System.out.println("如果你看见学生信息输出,则说明方法映射successfully");
- System.out.println("");
- }
- }
复制代码 |
|