根据类名,方法名反射
一.将所有加了@SocketController的类扫描并放入map中(程序启动时)
Reflections reflections1 = new Reflections("com.xxx.xxx"); // 获取所有加@SocketController注解的类 Set<Class<?>> set1 = reflections1.getTypesAnnotatedWith(SocketController.class); for(Class clazz : set1){ Annotation[] classAnnotations = clazz.getDeclaredAnnotations(); for(Annotation annotation : classAnnotations){ if(annotation instanceof SocketController){ SocketController socketController = (SocketController)annotation; // 注解的参数作为key String path = socketController.path(); classMap.put(path, clazz); } } }
二. 根据参数type从map中获取class, 并根据subType匹配到具体的方法,反射执行。
JSONObject contentJB = JSONObject.parseObject(content);
Class clazz = classMap.get(type);
Method[] methods = clazz.getMethods();
for(Method method : methods){
if(method.getName().equals(subType)){
SocketSession client = new SocketSession() {
@Override
public long getRoomID() {
return roomId;
}
@Override
public long getUID() {
return userId;
}
};
Object[] objects = new Object[contentJB.size()+1];
objects[0] = client;
// jsonobject对象中所有的key和value放入map中
Map<String, Object> fromParms = new HashMap<>();
for (Map.Entry<String, Object> entry : contentJB.entrySet()) {
fromParms.put(entry.getKey(), entry.getValue());
}
int i = 1;
Parameter[] parameters = method.getParameters();
// 根据方法的参数名,给参数赋值
for(Parameter parameter : parameters){
if("client".equals(parameter.getName())){
continue;
}
objects[i] = fromParms.get(parameter.getName());
i++;
}
// 反射相当于new了一个实例,想要用对象中通过spring注入进来的属性,需要从spring容器中获取对象实例。如下SpringUtil.getBean(clazz)
socketRet = (SocketRet) method.invoke(SpringUtil.getBean(clazz), objects);
}
}

浙公网安备 33010602011771号