Вопрос

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.
I know that if it's a RUNTIME, it may be read reflectively like this:

    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.

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. (However I wonder if it can do what you want)

Другие советы

You'll have to change the RetentionPolicy in the source code, unfortunately. There's no other way to make the annotation available for reflection at runtime, even in tests.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top