一个reflect的example
import java.lang.reflect.Field;
public class Mytest {
public static void main(String args[]) {
User u = new User();
u.setName("zhangshan");
u.setUid(100);
try{
changeValue(u);
}catch (Exception e)
{
e.printStackTrace();
}
System.out.print(u.getName()+":"+u.getUid());
}
public static void changeValue(Object obj)throws Exception{
Class c = obj.getClass();
Field[] fs = c.getDeclaredFields();
for(Field field:fs){
Class filedType = field.getType();
field.setAccessible(true);
if(filedType == int.class)
{
int oldValue = field.getInt(obj);
field.set(obj, oldValue + 100);
}
if(filedType == String.class)
{
String oldValue = (String)field.get(obj);
if(oldValue != null)
{
field.set(obj,oldValue.toUpperCase());
}
}
}
}
}