在运行时利用反射分析对象,其实就是利用反射来获得或者设置类的域。举例如下:
有一个Student类:
package testreflection; public class Student { private String stuNum; public Student(String stuNum) { this.stuNum = stuNum; } }
利用反射来获得和设置Student类的stuNum域的测试代码如下:
package testreflection; import java.lang.reflect.Field; public class ObjectAnalyzerTest { public static void main(String[] args) { Student student = new Student("20101120244"); Class cl = student.getClass(); try { Field field = cl.getDeclaredField("stuNum"); // 这一句对于访问私有域的值是必须的 field.setAccessible(true); // 获得域 Object object = field.get(student); System.out.println(object); // 设置域 field.set(student, "20121120064"); Object object1 = field.get(student); System.out.println(object1); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
运行ObjectAnalyzerTest结果如下:
20101120244
20121120064