您可以按照以下方式执行此操作,这将使您完成 3) 和 4)。
取自java 注释处理器示例的示例
@SupportedAnnotationTypes( "com.javacodegeeks.advanced.processor.Immutable" )
@SupportedSourceVersion( SourceVersion.RELEASE_7 )
public class SimpleAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(final Set< ? extends TypeElement > annotations,
final RoundEnvironment roundEnv) {
for( final Element element: roundEnv.getElementsAnnotatedWith( Immutable.class ) ) {
if( element instanceof TypeElement ) {
final TypeElement typeElement = ( TypeElement )element;
for( final Element eclosedElement: typeElement.getEnclosedElements() ) {
if( eclosedElement instanceof VariableElement ) {
final VariableElement variableElement = ( VariableElement )eclosedElement;
if( !variableElement.getModifiers().contains( Modifier.FINAL ) ) {
processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR,
String.format( "Class '%s' is annotated as @Immutable,
but field '%s' is not declared as final",
typeElement.getSimpleName(), variableElement.getSimpleName()
)
);
}
}
}
}
// Claiming that annotations have been processed by this processor
return true;
}
}
另一种使用带有自定义处理程序的projectlombok的方法。
来自 GitHub Project Lombok 的内置处理程序示例。这个注解添加了 try catch 块
public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
@SneakyThrows
public void run() {
throw new Throwable();
}
}
这被处理为
public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);
}
}
public void run() {
try {
throw new Throwable();
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
您可以在同一个 Github/lombok 站点上找到处理程序代码。