是否可以使用 AspectJ 查找实现特定接口(interface)的所有类的列表。例如,我有一个接口(interface) MatchRule
。然后我可以有类 DefaultMatchRule
和 CustomMatchRule
实现 MatchRule
接口(interface)的具体类。
现在在运行时我想获得一个列表,其中包含 2 个类 DefaultMatchRule
和 CustomMatchRule
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/