《java学习(175):类反射机制.docx》由会员分享,可在线阅读,更多相关《java学习(175):类反射机制.docx(3页珍藏版)》请在金锄头文库上搜索。
1、java学习(175):method类反射机制/class反射编程/定义一个学生类public class test124 public String name; protected int age; double height; private double money; public void setName(String name) this.name = name; public String getName() return name; public int getAge() return age; public void setAge(int age) this.age = age
2、; public test124(String name, Integer age) this.name=name; this.age=age; System.out.println( 调用有参构造方法 ); public test124(String name,int age,double money) this.name=name; this.age=age; this.money=money; /看书 public void learn(BookRead book) System.out.println( 我的名字+name+ 我正在学习+book.getName(); /奔跑 publ
3、ic void run() System.out.println( 我们喜欢奔跑 ); 定义一个method类import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;/method类反射机制public class test129 public static void main(String args) try Class stuCla = Class.forName( test124 ); test124 stuObj=new test124( geyao
4、,12 ); BookRead book=new BookRead(); book.setName( 歌谣 ); Method learnMet=stuCla.getMethod( learn, BookRead.class); learnMet.invoke( stuObj,book ); /获取非公共方法 Method runMet=stuCla.getDeclaredMethod( run); if(!runMet.isAccessible() runMet.setAccessible( true ); runMet.invoke( stuObj ); catch (Exception e) e.printStackTrace(); 定义一个bookread类public class BookRead private String name; public void setName(String name) this.name = name; public String getName() return name; 运行结果