我需要从各种类中检索一些带注释的方法。我正在使用此代码:

    Reflections reflections = new Reflections(
            new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("my.package"))
            .setScanners(new MethodAnnotationsScanner())
            );


    Set<Method> resources =
        reflections.getMethodsAnnotatedWith(org.testng.annotations.Test.class);


我找到了反射类的代码。但是,这段代码是针对整个package的(并且由于某种原因,该代码返回了我项目中的所有带注释的方法,而不仅仅是返回指定的包)。

但是,我只想从一个特定的类中获取带注释的方法。我不能在反射javadoc的正面或反面。

如何更改构造函数,以便仅返回来自特定类的带注释的方法?

最佳答案

您将需要使用输入过滤器来排除其他类。这是一个示例(请注意:如果MyClass中嵌套了任何类,那么它们也将被匹配。)

    final String className = MyClass.class.getCanonicalName();
    final Predicate<String> filter = new Predicate<String>() {
        public boolean apply(String arg0) {
            return arg0.startsWith(className);
        }
    };

    Reflections reflections = new Reflections(
            new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forClass(MyClass.class))
            .filterInputsBy(filter)
            .setScanners(new MethodAnnotationsScanner()));

    Set<Method> resources =
            reflections.getMethodsAnnotatedWith(org.testng.annotations.Test.class);

关于java - 使用org.reflection从Java中的特定类获取带注释的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32487144/

10-10 18:00