java - 使用Aspectj查找实现某个接口(interface)的类列表

标签 java aspectj

是否可以使用 AspectJ 查找实现特定接口(interface)的所有类的列表。例如,我有一个接口(interface) MatchRule。然后我可以有类 DefaultMatchRuleCustomMatchRule 实现 MatchRule 接口(interface)的具体类。 现在在运行时我想获得一个列表,其中包含 2 个类 DefaultMatchRuleCustomMatchRule

public interface MatchRule {

}

public class DefaultMatchRule implements MatchRule {

}

public class CustomMatchRule implements MatchRule {

}

public aspect FindSubClasses {

// some thing to find list of classes implementing MatchRule interface

}

最佳答案

AspectJ 不是为查找类而设计的。最好的选择是扫描类路径并使用反射。

如果您可以接受编译时信息,Eclipse AJDT 插件会为所有 AspectJ 建议提供良好的图形信息。

但是如果您可以忍受一些限制,您可以找到 AspectJ 建议的所有对象的类。

打印出实现 MatchRule 类的所有对象的类名的解决方案:

@Aspect
public class FindSubClassesAspect {

    @Pointcut("execution(demo.MatchRule+.new(..))")
    public void demoPointcut() {
    }

    @After("demoPointcut()")
    public void afterDemoPointcut(
            JoinPoint joinPoint) {
        FindSubClasses.addMatchRuleImplememtation(
                joinPoint.getTarget().getClass().getSimpleName());
    }
}

包含所有 MatchRule 实现信息的类:

public enum FindSubClasses {    
    ;

    private static Set<String> matchRuleImplementations = 
        new HashSet<String>();

    public static void addMatchRuleImplememtation(String className) {
        matchRuleImplementations.add(className);
    }

    public static Collection<String> getMatchRuleImplementations() {        
        return matchRuleImplementations;
    }
}

演示该方面有效的简单驱动程序:

public class Driver {
    public static void main(String[] args) {
        new DefaultMatchRule();
        new CustomMatchRule();

        Collection<String> matchRuleImplementations = 
            FindSubClasses.getMatchRuleImplementations();

        System.out.print("Clases that implements MatchRule: ");
        for (String className : matchRuleImplementations) {
            System.out.print(className + ", ");
        }
    }
}

执行此驱动程序的输出:

Clases that implements MatchRule: DefaultMatchRule, CustomMatchRule,

希望对您有所帮助!

关于java - 使用Aspectj查找实现某个接口(interface)的类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7585707/

相关文章:

java - 尽管已经安装了合适的 eclipse 尚未启动

java - 下拉描述或可展开 View

java - 构建签名APK时android studio中的gradle问题

java - 在建议之前和之后传递对象?

java - 具有覆盖接口(interface)方法的特定注释的方法的切入点

java - 如何将字符串转换为表示小时、分钟和秒的日期对象

java - 如何使用 JSF Richfaces AJAX 向/从 bean 函数发送/接收数据?

java - 生产系统中的 AspectJ 加载时织入

tomcat - 使用 Tomcat 6 服务器启动应用程序时出现@annotation 错误

java - 莫斯基托 : "advice defined in ... has not been applied"