9

假设一个类定义了一个常量字段:

public class Foo {
  public static final int CONSTANT_FIELD = 3;
}

并假设注释接口声明如下:

public @interface Something {
  int value();
}

最后,假设注释使用如下:

@Something(Foo.CONSTANT_FIELD)

问题:在注释处理器中,我如何才能CONSTANT_FIELD从其用于设置值的元素中获取元素@Something


编辑:在问题本身中包含一个具体示例。

我有一个这样使用的注释:

@RuleDependency(recognizer = BQLParser.class,
                rule = BQLParser.RULE_statement,
                version = 0)

注释处理器需要知道这是在类RULE_statement中定义的常量。BQLParser如果我可以通过设置注释的属性直接访问Elementfor ,它将消除对属性的需要。此注解在实际应用程序中使用了数千次,并且始终只是常量的声明类型。解决这个问题会将注释的使用简化为:BQLParser.RULE_statementrulerecognizerrecognizerrule

@RuleDependency(rule = BQLParser.RULE_statement, version = 0)
4

2 回答 2

3

我能够使用 Compiler Trees API 实现此功能。

  1. 更新pom.xml以包含以下配置文件,以确保在默认情况下不引用tools.jar的系统上引用它。

    <profiles>
        <profile>
            <!-- Java 6 and earlier have java.vendor set to "Sun Microsystems Inc." -->
            <id>default-tools-6.jar</id>
            <activation>
                <property>
                    <name>java.vendor</name>
                    <value>Sun Microsystems Inc.</value>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>com.sun</groupId>
                    <artifactId>tools</artifactId>
                    <version>1.6</version>
                    <scope>system</scope>
                    <systemPath>${java.home}/../lib/tools.jar</systemPath>
                </dependency>
            </dependencies>
        </profile>
    
        <profile>
            <!-- Java 7 and later have java.vendor set to "Oracle Corporation" -->
            <id>default-tools.jar</id>
            <activation>
                <property>
                    <name>java.vendor</name>
                    <value>Oracle Corporation</value>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>com.sun</groupId>
                    <artifactId>tools</artifactId>
                    <version>1.6</version>
                    <scope>system</scope>
                    <systemPath>${java.home}/../lib/tools.jar</systemPath>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
    
  2. 覆盖Processor.init以获取Trees.

    @Override
    public void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        this.trees = Trees.instance(processingEnv);
    }
    
  3. 实现 a TreePathScanner<TypeMirror, Void>,用于获取分配给注释TypeMirror中属性的声明类型的 。rule

    private class AnnotationVisitor extends TreePathScanner<TypeMirror, Void> {
        @Override
        public TypeMirror visitAnnotation(AnnotationTree node, Void p) {
            for (ExpressionTree expressionTree : node.getArguments()) {
                if (!(expressionTree instanceof AssignmentTree)) {
                    continue;
                }
    
                AssignmentTree assignmentTree = (AssignmentTree)expressionTree;
                ExpressionTree variable = assignmentTree.getVariable();
                if (!(variable instanceof IdentifierTree) || !((IdentifierTree)variable).getName().contentEquals("rule")) {
                    continue;
                }
    
                return scan(expressionTree, p);
            }
    
            return null;
        }
    
        @Override
        public TypeMirror visitAssignment(AssignmentTree at, Void p) {
            return scan(at.getExpression(), p);
        }
    
        @Override
        public TypeMirror visitMemberSelect(MemberSelectTree mst, Void p) {
            return scan(mst.getExpression(), p);
        }
    
        @Override
        public TypeMirror visitIdentifier(IdentifierTree it, Void p) {
            return trees.getTypeMirror(this.getCurrentPath());
        }
    }
    
  4. recognizer属性提供默认值。我希望这可能是null,但 Java 明确禁止...

    /**
     * Gets the recognizer class where the dependent parser rules are defined.
     * This may reference the generated parser class directly, or for simplicity
     * in certain cases, any class derived from it.
     * <p>
     * If this value is not specified, the default value {@link Parser}
     * indicates that the declaring type of the constant value specified for
     * {@link #rule} should be used as the recognizer type.
     * </p>
     */
    Class<? extends Recognizer<?, ?>> recognizer() default Parser.class;
    
  5. 更新收集有关RuleDependency应用于代码中特定Element实例的注释信息的代码,以首先尝试访问该recognizer属性,如果未指定,请改用该rule属性中常量的声明类型。为简洁起见,此代码示例中省略了错误处理。

    RuleDependency dependency = element.getAnnotation(RuleDependency.class);
    
    // first try to get the parser type from the annotation
    TypeMirror recognizerType = getRecognizerType(dependency);
    if (recognizerType != null && !recognizerType.toString().equals(Parser.class.getName())) {
        result.add(new Triple<RuleDependency, TypeMirror, Element>(dependency, recognizerType, element));
        continue;
    }
    
    // fallback to compiler tree API
    AnnotationMirror annotationMirror = null;
    for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
        if (processingEnv.getTypeUtils().isSameType(ruleDependencyTypeElement.asType(), mirror.getAnnotationType())) {
            annotationMirror = mirror;
            break;
        }
    }
    
    AnnotationValue annotationValue = null;
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) {
        if (entry.getKey().getSimpleName().contentEquals("rule")) {
            annotationValue = entry.getValue();
            break;
        }
    }
    
    TreePath treePath = trees.getPath(element, annotationMirror, annotationValue);
    AnnotationVisitor visitor = new AnnotationVisitor();
    recognizerType = visitor.scan(treePath, null);
    
    result.add(new Triple<RuleDependency, TypeMirror, Element>(dependency, recognizerType, element));
    
于 2014-03-15T17:17:51.100 回答
1

如果ruleint,注释处理器将不可能找出它int的定义位置。但是,您可以对字段使用 anenum而不是 an ,并在其中将您的规则与对其解析器的引用进行分组。也许是这样的:intrule

解析器接口:

public interface RuleParser {
}

示例实现:

public class RuleParserImpl implements RuleParser {
}

规则枚举:

public enum Rule {

    RULE_STATEMENT(RuleParserImpl.class);

    private final Class<? extends RuleParser> ruleParserClass;

    private Rule(Class<? extends RuleParser> ruleParser) {
        this.ruleParserClass = ruleParser;
    }

    public Class<? extends RuleParser> getRuleParserClass() {
        return ruleParserClass;
    }
}

使用 enum 而不是 int 字段的注释:

@Retention(RetentionPolicy.RUNTIME)
public @interface RuleDependency {
    Rule rule();
}

使用示例:

@RuleDependency(rule = Rule.RULE_STATEMENT)
public class RuleProcessor {

    public static void main(String[] args) {
        RuleDependency ruleDependency = RuleProcessor.class.getAnnotation(RuleDependency.class);
        Rule rule = ruleDependency.rule();
        Class<? extends RuleParser> ruleParserClass = rule.getRuleParserClass();
        System.out.println(ruleParserClass); //Prints "class RuleParserImpl"
    }
}

希望能给你一些想法。

于 2014-03-14T21:14:05.060 回答