开发者

Use Aspectj to find List of classes implementing a certain interface

Is it possible using AspectJ to find a list of all Classes which implement a certain interface. For e.g I have an interface MatchRule. Then I can have classes DefaultMatchRule and CustomMatchRule concrete clases which implement MatchRule interface. Now at runtime I want to get a list which will have 2 classes DefaultMatchRule and CustomMatchRule

public interface MatchRule {

}

public class DefaultMatchRule implements MatchRule {

}

public class CustomMatchRule implements MatchRule {

}
开发者_如何学JAVA
public aspect FindSubClasses {

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

}


AspectJ is not designed to finding classes. Your best option is to scan the classpath and use reflection.

If you can live with compile-time information, the Eclipse AJDT plugin offers good graphical information for all AspectJ advises.

But if you can live with some limitations, you can find the classes for all objects that is advised by AspectJ.

A solution that prints out the class names for all objects of classes that implements 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());
    }
}

A class that contain the information about all the MatchRule implementations:

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;
    }
}

A simple driver that demonstrate that the aspect works:

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

The output of executing this driver:

Clases that implements MatchRule: DefaultMatchRule, CustomMatchRule,

I hope this helps!


The only possible way to do this at runtime is probably scanning all your packages and checking to see whether your classes implement that interface.

I can't think of any other way this is possible. In fact, Eclipse has a context menu option that shows the "Implementors" of an interface but they achieve that by scanning the packages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜