问题描述
我启动了一个好玩,没人知道,没人关心"的开源项目( LinkSet ).
I started a "for fun, nobody knows, nobody cares" open source project (LinkSet).
在一个地方,我需要获得一个带注释的类的方法.
In one place I need to get an annotated method of a class.
有没有比这更有效的方法了?我的意思是不需要遍历每种方法吗?
Is there a more efficient way to do it than this? I mean without the need of iterating through every method?
for (final Method method : cls.getDeclaredMethods()) {
final HandlerMethod handler = method.getAnnotation(HandlerMethod.class);
if (handler != null) {
return method;
}
}
推荐答案
看看 Reflections (依赖项:番石榴和 Javassist ).这是一个已经对所有内容进行了优化的库.有一个符合您功能要求的 Reflections#getMethodsAnnotatedWith()
.
Take a look for Reflections (dependencies: Guava and Javassist). It's a library which has already optimized the most of it all. There's a Reflections#getMethodsAnnotatedWith()
which suits your functional requirement.
这是一个 SSCCE ,只需复制"n'paste'n'运行它即可.
Here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow;
import java.lang.reflect.Method;
import java.util.Set;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class Test {
@Deprecated
public static void main(String[] args) {
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("com.stackoverflow"))
.setScanners(new MethodAnnotationsScanner()));
Set<Method> methods = reflections.getMethodsAnnotatedWith(Deprecated.class);
System.out.println(methods);
}
}
这篇关于有没有更有效的方法来获取带注释的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!