Skip to content

Instantly share code, notes, and snippets.

@XDean
Last active Jul 20, 2018
Embed
What would you like to do?
Code snapshot for stackoverflow question 51358016
public @interface Anno {
String value();
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class HelloWorldProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
try {
FileObject resource = processingEnv.getFiler().createSourceFile("HelloWorldMessage");
PrintWriter ps = new PrintWriter(resource.openWriter());
ps.println("public interface HelloWorldMessage { String HELLO_WORLD = \"Hello World\";}");
ps.close();
} catch (IOException e) {
// Ignore, it may throw resource already exist exception which is not matter
}
}
return false;
}
}
public class UseHelloWorld {
public static final String HW = HelloWorldMessage.HELLO_WORLD;
@Anno(UseHelloWorld.HW) // This line fails
//@Anno(HelloWorldMessage.HELLO_WORLD) // This line works
public void bean() {
}
}
@XDean
Copy link
Author

XDean commented Jul 19, 2018

File structure

  • HelloWorldProcessor.java
  • Anno.java
  • UseHelloWorld.java

Step to reproduce

  • javac HelloWorldProcessor.java
  • javac -processor HelloWorldProcessor Anno.java UseHelloWorld.java

You can try to comment in UseHelloWorld#4 and comment out UseHelloWorld#5, it will work fine. (Don't forget clean all generated file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment