Can I get a class's name as a compile-time constant without hardcoding it in a string literal?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 23:05:40

Instead of using the annotation, your processor can implement getSupportedAnnotationTypes() to provide supported annotation type names at runtime:

Set<String> getSupportedAnnotationTypes() {
    Set<String> supportedAnnotationTypes = new HashSet<>();
    supportedAnnotationTypes.add(Foo.class.getName());
    return supportedAnnotationTypes;
} 



In case you'd like to keep using (non-standard) annotations for this, you could create your own annotation that takes a compile time type as argument, like @k_g suggested. @SupportedAnnotationTypes isn't really anything special, it is only used automatically when you are extending AbstractProcessor anyway. Take a look at the source code of AbstractProcessor.getSupportedAnnotationTypes().

The signature of your custom annotation should use Class<?>[] instead of String[]:

@Target(TYPE)
@Retention(RUNTIME)
public @interface SupportedAnnotationTypes {
    Class<?>[] value();
}

Override getSupportedAnnotationTypes and look up your custom annotation in the same way as AbstractProcessor. For example like this:

public Set<String> getSupportedAnnotationTypes() {
    Class<?>[] types = getClass().getAnnotation(SupportedAnnotationTypes.class).value();
    return Arrays.stream(types).map(Class::getName).collect(Collectors.toSet());
}

You can define your own.

public @interface SupportedAnnotationTypes_Class {
    Class supported();
}

and then use @SupportedAnnotationTypes_Class(supported = sand.Foo.class) to use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!