package com.co.lane.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* 反射处理
*
* @author Xuyd
*/
@SuppressWarnings("rawtypes")
public class ReflectUtil {
// 载入的类
private Class<?> clazz;
private Map<String, Field> mapField = new HashMap<String, Field>();
private Map<String, Method> mapSetMethod = new HashMap<String, Method>();
private Map<String, Method> mapGetMethod = new HashMap<String, Method>();
private ReflectUtil(Class type) {
this.clazz = type;
// add field
int modify = (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED);
for (Field f : clazz.getDeclaredFields()) {
if (f.getModifiers() < modify) {
mapField.put(f.getName().toLowerCase(), f);
}
}
// add method
for (Method m : clazz.getDeclaredMethods()) {
String name = m.getName();
if ((name.startsWith("get") && name.length() > 3)
|| (name.startsWith("is") && name.length() > 2)) {
if (m.getParameterTypes().length == 0) {
name = StringUtil.methodToProperty(name);
//mapGetMethod.put(name, m);
mapGetMethod.put(name.toLowerCase(), m);
}
} else if (name.startsWith("set") && name.length() > 3) {
if (m.getParameterTypes().length == 1) {
name = StringUtil.methodToProperty(name);
//mapSetMethod.put(name, m);
mapSetMethod.put(name.toLowerCase(), m);
}
}
}
}
public static ReflectUtil forClass(Class type) {
return new ReflectUtil(type);
}
/**
* 查找字段名是否存在
*
* @param name
* @return
*
*/
public boolean hasField(String name) {
if (mapField.get(name) == null) {
return false;
//throw new RuntimeException("field " + name + " is not exists!");
}
return true;
}
/**
* 查找方法名是否存在
*
* @param name
* @return
*/
public boolean hasMethod(String name) {
if (mapSetMethod.get(name) == null || mapGetMethod.get(name) == null) {
throw new RuntimeException(name + "'s get method and set method are not exists!");
}
return true;
}
/**
* @return the clazz
*/
public Class<?> getClazz() {
return clazz;
}
/**
* 设置属性值
*
* @param instance
* @param name
* @param value
* @return
*/
public void setSetMethodValue(Object instance, String name, Object value) {
name = name.toLowerCase();
if (hasField(name) && mapSetMethod.get(name) != null) {
try {
Method m = mapSetMethod.get(name);
m.invoke(instance, StringUtil.convertDataType(m.getParameterTypes()[0], value));
} catch (Exception e) {
e.printStackTrace();
StringUtil.trace(e.getMessage() + "\nfield:" + name);
}
}
}
/**
* 获取属性值
*
* @param instance
* @param name
* @return
*/
public Object getGetMethodValue(Object instance, String name) {
name = name.toLowerCase();
Object ret = null;
if (hasField(name) && mapGetMethod.get(name) != null) {
try {
ret = mapGetMethod.get(name).invoke(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
}