通过反射调用方法和操作属性
为了演示,我们先改下Student类:
package com.java1234.chap07.sec04; public class Student { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public void say(){ System.out.println("我的姓名:"+name); } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }
1,通过反射调用方法,主要通过invoke方法,我们给下演示代码:
package com.java1234.chap07.sec04; import java.lang.reflect.Method; public class Test1 { public static void main(String[] args) { Class<?> c=null; try { c=Class.forName("com.java1234.chap07.sec04.Student"); System.out.println(c.getName()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Object obj=c.newInstance(); Method m2=obj.getClass().getMethod("setName", String.class); m2.invoke(obj, "小锋"); Method m=obj.getClass().getMethod("getName"); String name=(String) m.invoke(obj); System.out.println("name="+name); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2,通过反射操作属性,java里反射可以操作私有属性,只需要设置下,我们给下演示代码:
package com.java1234.chap07.sec04; import java.lang.reflect.Field; public class Test2 { public static void main(String[] args) { Class<?> c=null; try { c=Class.forName("com.java1234.chap07.sec04.Student"); System.out.println(c.getName()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Object obj=c.newInstance(); Field nameField=c.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(obj, "小锋"); System.out.println("name="+nameField.get(obj)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行输出:
com.java1234.chap07.sec04.Student
name=小锋
上一篇:通过反射获取类的基本结构
下一篇:第七章 Java反射作业