您可以在下面执行此操作,这将使您完成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;
}
}
使用具有自定义处理程序的投影龙目的另一种方法。
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网站上找到Handler代码。