在项目中多处使用到反射方法,jdk为1.5.现总结如下:
1.设置java对象的指定属性为指定值,调用set方法:
/**
* 使用反射机制进行设置值.
* @param o 对象
* @param name 要设置的属性
* @param value 要设置的value
*/
public static void setPro(Object o, String name, String value) {
PropertyDescriptor[] props;
try {
props = Introspector.getBeanInfo(o.getClass(), Object.class)
.getPropertyDescriptors();
for (int temp = 0; temp < props.length; temp++) {
if (name.equals(props[temp].getName())) {
try {
props[temp].getWriteMethod().invoke(o, value);
} catch (Exception e) {
}
break;
}
}
} catch (IntrospectionException e1) {
e1.printStackTrace();
}
}
2.得到java bean里面的属性值
/**
* 得到指定对象的指定属性值.
* @param o 对象
* @param name 属性名
* @return
*/
public static String getPro(Object o, String name) {
String result = "";
PropertyDescriptor[] props;
try {
props = Introspector.getBeanInfo(o.getClass(), Object.class)
.getPropertyDescriptors();
for (int temp = 0; temp < props.length; temp++) {
if (name.equals(props[temp].getName())) {
try {
result = props[temp].getReadMethod().invoke(o)
.toString();
} catch (Exception e) {
}
break;
}
}
return result;
} catch (IntrospectionException e1) {
e1.printStackTrace();
return null;
}
}
3.打印一个java bean里面的全部的get方法:
public static void getAllGets(Object o) {
Method[] method = o.getClass().getMethods();
try {
for (int i = 0; i < method.length; i++) {
//如果方法名是含有get的名称,而且是返回的string类型,以及参数个数为空,就调用该方法。
if (method[i].getName().indexOf("get") != -1
&& method[i].getGenericReturnType().toString().indexOf(
"String") != -1
&& method[i].getGenericParameterTypes().length == 0) {
System.out.println(i + method[i].getName() + "():\n"
+ method[i].invoke(o, null));
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
4.得到一个对象里面全部返回值为string类型的方法:
/**
* 得到一个对象的返回string的全部方法.
* @param o
*/
public static List<String> getAllMethods(Object o) {
Method[] method = o.getClass().getMethods();
List<String> methods = new ArrayList();
try {
for (int i = 0; i < method.length; i++) {
//如果方法名是含有get的名称,而且是返回的string类型,以及参数个数为空,就调用该方法。
if ( method[i].getGenericReturnType().toString().indexOf(
"String") != -1
&& method[i].getGenericParameterTypes().length == 0) {
methods.add(method[i].getName());
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return methods;
}
5.得到一个对象的全部属性
/**
* 得到一个对象的全部属性值.
* @param o
* @return 属性名和属性值的映射
*/
public static Map getAllProperties(Object o) {
Map ans = new HashMap();
PropertyDescriptor[] props;
try {
props = Introspector.getBeanInfo(o.getClass(), Object.class)
.getPropertyDescriptors();
for (int temp = 0; temp < props.length; temp++) {
String result = null;
if(props[temp].getReadMethod().invoke(o)!=null)
result = props[temp].getReadMethod().invoke(o).toString();
ans.put(props[temp].getName(), result);
}
} catch (Exception e1) {
e1.printStackTrace();
}
return ans;
}
6.返回对象中设置了get方法的属性的集合
/**
* 返回对象中设置了get方法的属性的集合,注意集合的成员是Field对象!
* @param obj
* @return
*/
public static List<Field> allAttrWithGetMethod(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
Method[] methods = obj.getClass().getMethods();
List result = new ArrayList();
for (Field field : fields) {
String fieldName = field.getName();
String upperFirstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + upperFirstLetter
+ fieldName.substring(1);
for (Method method : methods) {
if (Util.equals(getMethodName, method.getName())) {
result.add(field);
}
}
}
return result;
}
7.执行指定对象的无参方法:
/**
* 使用反射执行指定对象的无参方法,返回结果是一个对象.
* @param obj 对象
* @param methodName 方法名
* @return
* @throws MVCException
*/
public static Object invoke(Object obj, String methodName) throws Exception,MVCException {
try {
//如果没有配置method参数就默认的使用execute()方法。
if(Util.isEmpty(methodName))
methodName = "execute";
if(!getAllMethods(obj).contains(methodName)){
throw new MVCException(obj.getClass().getName()+"反射执行方法中没有找到与"+methodName+"匹配的方法,或者没有execute方法!");
}
Method method = obj.getClass().getMethod(methodName, null);
return method.invoke(obj, null);
}
catch (MVCException e) {
throw e;
}
catch (Exception e) {
throw e;
}
}
8.执行有参的私有方法:
/**
* 调用指定对象的私有方法
* @param object
* @param methodName
* @param params
* @return
* @throws NoSuchMethodException
*/
public static Object invokePrivateMethod(Object object, String methodName,
Object... params) throws NoSuchMethodException {
Assert.notNull(object);
Assert.hasText(methodName);
//得到参数数组的类型,后面将根据这个查找指定的方法对象.
Class[] types = new Class[params.length];
for (int i = 0; i < params.length; i++) {
types[i] = params[i].getClass();
}
Class clazz = object.getClass();
Method method = null;
//向上转型一直找到基类里面的方法.
for (Class superClass = clazz; superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
//两个参数表示:方法名,方法中的参数数组.
//返回方法对象.
method = superClass.getDeclaredMethod(methodName, types);
break;
} catch (NoSuchMethodException e) {
}
}
if (method == null)
throw new NoSuchMethodException(clazz.getSimpleName()+" No Such Method:"
+ methodName);
//先保存以前的可访问性
boolean accessible = method.isAccessible();
method.setAccessible(true);
Object result = null;
try {
result = method.invoke(object, params);
} catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
}
method.setAccessible(accessible);
return result;
}
9.BeanUtils工具类
import org.apache.commons.beanutils.BeanUtils;
public static void main(String[] args){
Chart s = new Chart();
try {
Map m = BeanUtils.describe(s);
System.out.println(m.keySet());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}