使用Aspectj查找实现某个接口的类列表

时间:2011-09-28 15:35:07

标签: java aspectj

是否可以使用AspectJ查找实现某个接口的所有类的列表。例如,我有一个接口MatchRule。然后我可以使用实现DefaultMatchRule接口的类CustomMatchRuleMatchRule具体条款。 现在,在运行时,我想获得一个列表,其中包含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

}

2 个答案:

答案 0 :(得分:1)

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 + ", ");
        }
    }
}

执行此驱动程序的输出:

  

实现MatchRule的Clases:DefaultMatchRule,CustomMatchRule,

我希望这有帮助!

答案 1 :(得分:0)

在运行时执行此操作的唯一可能方法是扫描所有包并检查您的类是否实现该接口。

我想不出任何其他方式这是可能的。事实上,Eclipse有一个上下文菜单选项,可以显示界面的“实现者”,但是他们通过扫描包来实现这一点。

相关问题