package com.javaluna.reflect; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; public class ReflectDemo01{ @Test public void test0() throws Exception{ Person person=new Person(); 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()); } } class Person{ private Integer id; private String name; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
关于反射详解:http://www.cnblogs.com/onlywujun/p/3519037.html