编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象,并调用该对象中的方法。对反射的进一步深化理解,我增加了很多反射的代码,可以仔细看看,参考一下。。。- [hide]class StudentTest {
- String name;
- int age;
- String sex;
- StudentTest(String name,int age,String sex)
- {
- this.name=name;
- this.age=age;
- this.sex=sex;
- }
- public void StuInfo()
- {
- System.out.println("["+name+","+age+","+sex+"]");
- }
- }
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- Class c = Class.forName("com.itheima.StudentTest");
- Constructor cs = c.getDeclaredConstructor(String.class,int.class,String.class);
- StudentTest stu =(StudentTest)cs.newInstance("zhangsan",32,"Man");
- stu.StuInfo();
-
- stu.getClass().getDeclaredMethod("StuInfo").invoke(new StudentTest("wangwu",12,"Man"));
-
- Field[] fileds=stu.getClass().getDeclaredFields();
- for(Field field : fileds)
- {
- if(field.getName().equals("name"))
- field.set(stu, "zhaoliu");
- System.out.println(field.getName()+":"+field.get(stu));
- }
- Field f = stu.getClass().getDeclaredField("name");
- System.out.println(f.getName()+"..."+f.get(stu));
- }
- [/hide]
复制代码
|