自定义注解并获取所有带有该注解的方法
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Handler {
String request();
}
- 注解定义
public class ClassUtils {
public static String RootPath = new File("").getAbsolutePath();
public static String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
private static List<Class> getAllClasses(File file, List<Class> classes) throws ClassNotFoundException {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) getAllClasses(f, classes);
} else {
if (file.getName().endsWith(".class")) {
String className = file.getPath().replace(".class","").replace(classPath.replace("/","\\").substring(1),"").replace("\\",".");
classes.add(Class.forName(className));
}
}
return classes;
}
public static List<Class> getAllClasses() throws ClassNotFoundException {
List<Class> list = new ArrayList<>();
list = getAllClasses(new File(classPath), list);
return list;
}
public static List<Class> getAllClasses(String path) throws ClassNotFoundException {
List<Class> list = new ArrayList<>();
list = getAllClasses(new File(path), list);
return list;
}
}
RootPath
为项目根
路径classPath
为class
路径getAllClasses
获取指定目录(或根目录)下所有的.class
public class AnnotationUtils {
public static Map<String, Method> getAllHandler() throws ClassNotFoundException {
Map<String, Method> map = new ConcurrentHashMap<>();
List<Class> list = ClassUtils.getAllClasses();
list.forEach(aClass -> {
List<Method> methodList = List.of(aClass.getMethods());
methodList.forEach(aMethod ->{
if (aMethod.getAnnotation(Handler.class) != null){
map.put(aMethod.getAnnotation(Handler.class).request().toString(), aMethod);
}
});
});
return map;
}
}
getAllHandler
获取 所有@Handler
方法
https://github.com/jt-jiangtao/lsp-server
github:lsp-server 基于netty的lsp服务器, 你可以用该框架编写vscode等编译器插件(插件后端)
水一篇文章
这两个工具类是lsp-server实现@Handler处理前端请求的核心
目前lsp-server项目仅仅完成核心部分,包括rpc 使用@Handler处理前端传来的请求