2011-09-28 52 views
3

是否可以使用AspectJ来查找实现某个接口的所有类的列表。例如,我有一个接口MatchRule。然后我可以通过类DefaultMatchRuleCustomMatchRule具体实现MatchRule接口。 现在在运行时我想这将有2班DefaultMatchRuleCustomMatchRule使用Aspectj查找实现某个接口的类的列表

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 

} 
+0

你能解释一下为什么你需要这样的清单吗?除了分析代码外,我无法想象这样的理由。在所有其他情况下,您可以在使用它们的时刻横切课程。 – alehro

回答

0

唯一可能的途径在运行时做到这一点可能是扫描所有的包和检查,看看你的类是否实现该接口列表。

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

+0

感谢您的回答;我认为,因为我可以在aspectj中定义一个切入点,例如* MatchRule +;会有像我可以获得这些信息的切入点上下文。我也看过PointCutParser,但找不到任何信息。 – user667022

1

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

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

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

打印出用于实现MatchRule类的所有对象的类名:A液

@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实现MatchRule:DefaultMatchRule,CustomMatchRule,

我希望这有助于!

相关问题