packagecom.javaluna.reflect; importjava.lang.reflect.Field; importjava.lang.reflect.Method; importorg.junit.Test; public classReflectDemo01{ @Test public void test0() throwsException{ Person person=newPerson(); person.setId(1); person.setName("张三"); person.setAddress("上海"); Class<? extends Person> c =person.getClass(); Field[] fields = c.getDeclaredFields();//获取所有属性字段 private public,但是不包含父类 for(Field f:fields){ f.setAccessible(true); String fieldName=f.getName(); if(fieldName.equals("address")){ f.set(person, "北京");//设置属性值 } Object fieldVal=f.get(person);//获取属性值 System.out.println("fieldName = "+fieldName+" fieldVal = "+fieldVal); } //直接获取某个字段值 Method m=c.getDeclaredMethod("getId"); System.out.println(m.invoke(person));//获取属性值 Method m1=c.getDeclaredMethod("setName",String.class); m1.invoke(person, "李四");//设置属性值 System.out.println(person.getName()); } } classPerson{ privateInteger id; privateString name; privateString address; publicInteger getId() { returnid; } public voidsetId(Integer id) { this.id =id; } publicString getName() { returnname; } public voidsetName(String name) { this.name =name; } publicString getAddress() { returnaddress; } public voidsetAddress(String address) { this.address =address; } }
关于反射详解:http://www.cnblogs.com/onlywujun/p/3519037.html