简体   繁体   English

如何从Java源代码中获取自定义注释?

[英]How to get custom annotation from source code in java?

I'm trying to use a custom annotation to get some statistics for unit test. 我正在尝试使用自定义注释来获取一些用于单元测试的统计信息。 Another guy has defined a custom annotation as follows: 另一个人定义了一个自定义注释,如下所示:

@Retention(RetentionPolicy.SOURCE)
@Target( { ElementType.METHOD, ElementType.TYPE})  
public @interface TimsID {
    String   id();
    String   description() default "";
}

What I need to do is extracting this annotation from all unit tests in our project. 我需要做的是从项目中的所有单元测试中提取此批注。

Here comes the problem: 问题来了:

the RetentionPolicy is defined as SOURCE , I don't know how to get it in the unit test. RetentionPolicy定义为SOURCE ,我不知道如何在单元测试中获取它。
I know that if it's a RUNTIME , it may be read reflectively like this: 我知道如果它是RUNTIME ,则可能会像这样反省地读取:

    Class<TestExample> obj = TestExample.class;

    // Process @TimsID
    if (obj.isAnnotationPresent(TimsID.class)) {

        Annotation annotation = obj.getAnnotation(TimsID.class);
        TimsID TimsID = (TimsID) annotation;
    }

But now it's 'SOURCE', annotations will not be recorded in the class file by the compiler or retained by the VM at run time, so they can't be read reflectively. 但是现在是“ SOURCE”,注释将不会由编译器记录在类文件中,也不会在运行时由VM保留,因此无法进行反射式读取。

The guy who defined the custom annotation said the reason he chooses "SOURCE" is that we just need to statistic this annotation in source code, we don't need to write these custom annotations in class file or even runtime, so we need annotation analysis only in source code. 定义自定义注释的人说,他之所以选择“源”,是因为我们只需要在源代码中统计此注释,就不需要在类文件甚至运行时中编写这些自定义注释,因此我们需要进行注释分析仅在源代码中。

I've accomplished this work, and here is the step and code . 我已经完成了这项工作, 这是步骤和代码

SOURCE retention is aimed to be used only during compilation process. 源保留旨在仅在编译过程中使用。 You may look into APT (Annotation Processing Tool) for more information on how to perform such kind of compile-time annotation processing logic. 您可以查看APT(注释处理工具)以获取有关如何执行这种编译时注释处理逻辑的更多信息。 (However I wonder if it can do what you want) (但是我想知道它是否可以满足您的要求)

You'll have to change the RetentionPolicy in the source code, unfortunately. 不幸的是,您必须在源代码中更改RetentionPolicy There's no other way to make the annotation available for reflection at runtime, even in tests. 没有其他方法可以使注释在运行时甚至在测试中也可以反射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM