花点时间弄的一个url和方法映射的小Demo,先记录在此,便于后面使用。
[color=red]Note:使用场景:Mina,Netty的Client->Server请求映射关系。[/color] 后期有时间再加上一个类级的映射,以达到模块划分之间的划分更清晰。
1、Mapper 映射关系的Annotation类。
2、UserService 这里用于测试的案例业务类。
3、Test 用于测试的类。
[color=red]Note:使用场景:Mina,Netty的Client->Server请求映射关系。[/color] 后期有时间再加上一个类级的映射,以达到模块划分之间的划分更清晰。
1、Mapper 映射关系的Annotation类。
package com.runant.demo;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* @author ping
*
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapper {
String value() default "";
}
2、UserService 这里用于测试的案例业务类。
package com.runant.demo;
/**
* @author ping
*
*/
@Mapper(value = "/user")
public class UserService {
@Mapper(value = "/getUser")
public String getUser(String userName) {
return "Hello...." + userName;
}
@Mapper(value = "/login")
public boolean login(String userName, String password) {
System.out.println("Login user-name:" + userName + ",password:" + password);
return "admin".equals(userName) && "123456".equals(password);
}
public boolean delete(String userName) {
System.out.println("Delete user-name:" + userName);
return true;
}
}
3、Test 用于测试的类。
package com.runant.demo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author ping
*
*/
public class Test {
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// String url = "/user/getUser";
String url = "/user/login";
String params = "Test ,Hahahha~!~";
Map<String, Invoker> urlMapping = new HashMap<String, Invoker>();
UserService service = new UserService();
Mapper topMapper = service.getClass().getAnnotation(Mapper.class);
String topUrl = topMapper != null ? topMapper.value() : "";
Method[] methods = service.getClass().getDeclaredMethods();
for (Method m : methods) {
Mapper subMapper = (Mapper) m.getAnnotation(Mapper.class);
if (subMapper != null) {
urlMapping.put(topUrl + subMapper.value(), new Invoker(service, m));
}
}
Invoker invoker = urlMapping.get(url);
// Object result = invoker.execute(params);
Object result = invoker.execute("Leo","123");
System.out.println(result);
result = invoker.execute("admin","123456");
System.out.println(result);
}
private static class Invoker {
private Method method;
private Object obj;
public Invoker(Object obj, Method method) {
this.obj = obj;
this.method = method;
}
public Object execute(Object... args){
try {
return this.method.invoke(obj, args);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
}