我有以下条件,它需要具有特定字段值的 Java 注释在类的任何字段中恰好出现一次。Java 8 可以吗?
我的注释
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //can use with fields only.
public @interface TestAnnotation{
public String id();
}
使用注释的类类似于
@TestAnnotation(id="test")
private String testString;
@TestAnnotation(id="test1")
private String test1String;
@TestAnnotation(id="test2")
private String test2String;
我想要的只是为了防止程序员使用类似的东西
@TestAnnotation(id="test2")
private String test2String;
@TestAnnotation(id="test2")
private String test3String;
即具有特定 ID @TestAnnotation(id="test2")
的相同注释不能在字段上使用两次。至少id="..."
在类@TestAnnotaion
应用字段中应该是唯一的。
您似乎已经想通了,这可以通过注释处理器来实现。
下面是一个示例:
package mcve.proc;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IDExample {
String id();
}
package mcve.proc;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import javax.tools.*;
import java.util.*;
@SupportedAnnotationTypes("mcve.proc.IDExample")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class UniqueIDProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Elements elements = processingEnv.getElementUtils();
Types types = processingEnv.getTypeUtils();
Map<TypeElement, Set<VariableElement>> map = new HashMap<>();
// Find each of the fields annotated with @IDExample.
for (Element elem : roundEnv.getElementsAnnotatedWith(IDExample.class)) {
if (elem.getKind() == ElementKind.FIELD) {
VariableElement var = (VariableElement) elem;
TypeElement decl = (TypeElement) var.getEnclosingElement();
// Group them by declaring class.
map.computeIfAbsent(decl, key -> new HashSet<>()).add(var);
}
}
// Now for each set of fields annotated with @IDExample...
for (Set<VariableElement> fields : map.values()) {
Map<String, Set<VariableElement>> fieldsByID = new HashMap<>();
// Group them by ID.
for (VariableElement field : fields) {
String id = field.getAnnotation(IDExample.class).id();
fieldsByID.computeIfAbsent(id, key -> new HashSet<>()).add(field);
}
fieldsByID.forEach((String id, Set<VariableElement> fieldsWithID) -> {
// For each set of fields which have duplicate IDs,
// cause a compilation error on each annotation.
if (fieldsWithID.size() > 1) {
for (VariableElement field : fieldsWithID) {
// This is all just finding the annotation mirror so
// the compilation error appears in the right place.
TypeMirror idExampleMirror =
elements.getTypeElement(IDExample.class.getName()).asType();
AnnotationMirror annotation =
field.getAnnotationMirrors().stream()
.filter(mirror -> types.isSameType(idExampleMirror, mirror.getAnnotationType()))
.findFirst().get();
AnnotationValue value =
annotation.getElementValues().entrySet().stream()
.filter(e -> e.getKey().getSimpleName().contentEquals("id"))
.map(e -> e.getValue())
.findFirst().get();
// Actually cause the compilation error.
String errorMessage = String.format(""%s" is a duplicate ID.", id);
processingEnv.getMessager()
.printMessage(Diagnostic.Kind.ERROR,
errorMessage,
field,
annotation,
value);
}
}
});
}
return false;
}
}
这里有一个关于如何使注释处理工作的教程。例如,要使上述示例处理器正常工作,您需要大致执行以下操作(我假设取决于您的 IDE(:
- 为两个类
mcve.proc.IDExample
和mcve.proc.UniqueIDProcessor
创建一个项目/单独的 jar。 - 在该 jar 中,创建一个目录
META-INF/services
。 - 在该目录中,创建一个名为
javax.annotation.processing.Processor
(无文件扩展名(的文本文件,其内容是注释处理器mcve.proc.UniqueIDProcessor
的完全限定名。 - 将该项目/jar 作为库导入到主项目中。
- 如果存在/需要这样的设置,可以在例如项目属性中添加
mcve.proc.UniqueIDProcessor
作为注释处理器。我知道 Netbeans 就是这样做的。我不知道其他IDE。