package com.hunau.liuyong;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
//其中User就是一个bean,里面就一个name属性
public class Test {
public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
User user=new User();
List list=new ArrayList();
list.add(user);
System.out.print("+++++++");
Method method=getSetMethod(list.get(0).getClass(),"name");
System.out.print("+++++++");
method.invoke(list.get(0),"liuyong");
method=getGetMethod(list.get(0).getClass(),"name");
System.out.println(method.invoke(list.get(0),null));
}
public static Method getGetMethod(Class objectClass,String fieldName) throws SecurityException, NoSuchMethodException{
System.out.print("+++++++");
StringBuffer sb=new StringBuffer();
sb.append("get");
sb.append(fieldName.substring(0,1).toUpperCase());
sb.append(fieldName.substring(1));
Method method=objectClass.getMethod(sb.toString(), null);
System.out.print("+++++++");
return method;
}
public static Method getSetMethod(Class objectClass,String fieldName) throws SecurityException, NoSuchMethodException, NoSuchFieldException{
Class[] parameterTypes=new Class[1];
Field field=objectClass.getDeclaredField(fieldName);
System.out.println("dasg");
parameterTypes[0]=field.getType();
StringBuffer sb=new StringBuffer();
System.out.println("dasg");
sb.append("set");
sb.append(fieldName.substring(0,1).toUpperCase());
sb.append(fieldName.substring(1));
System.out.println(fieldName);
Method method=objectClass.getMethod(sb.toString(), parameterTypes);
System.out.println("dasg");
return method;
}
}