在学习java的时候,学过反射机制,但是真正用到的机会很少。
两年中也就用到两次
1.给第三方提供接口,每个接口都需要统计响应时间
2.Map和Bean的转化
统计响应时间 大致思路如下
1.给用户提供统一接口,将具体方法和参数放到post的参数中,传过来。
2.服务器响应后,记录当前时间。
3.判断方法参数是否存在
3.利用映射得到接口方法类,然后将method和parameter传进去
4.得到相应结果
5.记录结束时间
6.返回结果给用户
部分代码
@ResponseBody
@RequestMapping(value = "/api", method = {RequestMethod.GET, RequestMethod.POST})
public Map<String, Object> api(HttpServletRequest request) {
long startTime = System.currentTimeMillis();
long totalTime=0;
Map<String, Object> resultMap = new HashMap<String, Object>();
String method = request.getParameter("method");
if (method == null || method.isEmpty()) {
;
} else {
try {
Class<?> c = Class.forName("com.Api");
Map<String, Object> invokeMap = (Map<String, Object>) c.getMethod(method, HttpServletRequest.class, Map.class).invoke(c.newInstance(), new Object[]{request});
} catch (NoSuchMethodException e) {
}
totalTime= System.currentTimeMillis()-startTime;
return resultMap;
}
totalTime= System.currentTimeMillis()-startTime;
return resultMap;
}
Map和Bean的转化,代码如下(复杂的类会报空指针错误)
public class BeanUtil {
public static Map<String,Object> transBean2Map(Object obj){
if(obj==null){
return null;
}
Map<String,Object> map=new HashMap<String,Object>();
try{
BeanInfo beanInfo= Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
String key=propertyDescriptor.getName();
if(!key.equals("class")){
Method method=propertyDescriptor.getReadMethod();
if(method!=null){
Object value=method.invoke(obj);
map.put(key,value);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return map;
}
public static void transMap2Bean(Map<String,Object>map,Object obj){
try{
BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
String key=propertyDescriptor.getName();
if(map.containsKey(key)){
Object value=map.get(key);
Method method=propertyDescriptor.getWriteMethod();
method.invoke(obj,value);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}