package com.gyarmy.person; import java.lang.reflect.Field; import org.junit.Test; public class TestPerson { @Test public void test2() throws Exception{ Class cls1 = Class.forName("com.gyarmy.person.Person"); Field nameField = cls1.getDeclaredField("name"); //打开访问权限 nameField.setAccessible(true); Person p1 = new Person(); nameField.set(p1, "百度"); System.out.println(p1.getName()); } //测试反射 @Test public void test1() throws ClassNotFoundException{ //互殴字节码 Class cls1 = Class.forName("com.gyarmy.person.Person"); Class cls2 = new Person().getClass(); Class cls3 = Person.class; System.out.println("cls1 = "+cls1); System.out.println("cls2 = "+cls2); System.out.println("cls3 = "+cls3); } }
0则评论给“反射简单测试”