【发布时间】:2015-12-01 00:51:22
【问题描述】:
我有一个注释,它标记包含实现命名接口的内部类的类。
以下是如何使用此注解的示例:
public interface Implementable {}
@Deserializable(Implementable.class)
public class ImplementableFactory {
public static Implementable getImplementable() {
return new Impl();
}
private class Impl implements Implementable {}
}
这是注释本身:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public @interface Deserializable {
Class value();
}
我想做一些注释处理来确保这个合同。为此,我创建了一个注释处理器类:
public class DeserializableProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for(Element element : roundEnv.getElementsAnnotatedWith(Deserializable.class)){
TypeMirror expected = getDeserializableValue(element);
if (expected != null) {
Boolean found = false;
for (Element enclosed : element.getEnclosedElements()) {
if (enclosed.getKind().equals(ElementKind.CLASS)) {
//This next bit doesn't compile.
//I'm looking for the same functionality.
if (expected.isAssignableFrom(enclosed)) {
found = true;
break;
}
}
}
if (!found) {
String message = String.format("Classes marked with the Deserializable annotation must contain an inner class with implements the value of the annotation. %s does not contain a class which implements %s.",
element.getSimpleName().toString(),
expected.toString());
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
}
}
}
return true;
}
private TypeMirror getDeserializableValue(Element element) {
...
}
}
如何在可能通过注释处理的反射中实现与 Class::isAssignableFrom 类似的功能?
【问题讨论】:
标签: java reflection annotations annotation-processing