Java annotation values are provided dynamically

I want to provide comments for some values generated by some methods

I've tried so far

public @interface MyInterface {
    String aString();
}
@MyInterface(aString = MyClass.GENERIC_GENERATED_NAME)
public class MyClass {

    static final String GENERIC_GENERATED_NAME = MyClass.generateName(MyClass.class);

    public static final String generateName(final Class<?> c) {
        return c.getClass().getName();
    }
}

Thought generic_ GENERATED_ Name is static. Finally, it complains

So how to achieve it?

Solution

There is no way to dynamically generate strings used in comments The compiler evaluates retentionpolicy at compile time Annotation metadata for runtime annotations, but before runtime, generic_ GENERATED_ I don't know And you can't be retentionpolicy The source annotation uses the generated values because they are discarded at compile time, so these generated values will never be known

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>