Skip to content

Instantly share code, notes, and snippets.

@XDean
Last active July 20, 2018 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XDean/29a225f631cefbc75752b6a35b5ccb28 to your computer and use it in GitHub Desktop.
Save XDean/29a225f631cefbc75752b6a35b5ccb28 to your computer and use it in GitHub Desktop.
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