Blessed Geek
Blessed Geek

Reputation: 21674

How to step-debug annotation processor during compile?

I have an annotation processor for an annotation of retention policy=SOURCE.

I have not idea how to step-debug it.

Upvotes: 10

Views: 5423

Answers (3)

bryant1410
bryant1410

Reputation: 6370

Annotation processing occurs during compilation, so normal debugging won't work. If you want to debug it in the context of you project, you can use Eclipse remote debugging, while having Gradle or Maven in debug mode. Then you can put breakpoints in the Annotation Processor's files.

See Debugging an Annotation Processor in any project.

Disclaimer: I wrote the post.

Upvotes: 2

Christian Gruber
Christian Gruber

Reputation: 4761

An option in recent times is to use something like http://github.com/google/compile-testing which lets you invoke the compilation job against arbitrary annotation processors, which you can set break points, step through, etc.

@Test public void testStuff() {
  // Create a source file to process, or load one from disk.
  JavaFileObject file = JavaFileObjects.fromSourceLines("test.Foo",
    "package test;",
    "",
    "import bar.*;",
    "",
    "@MyAnnotation(blah=false)",
    "interface TestInterface {",
    "  Bar someBar();",
    "}",

  // assert conditions following a compilation in the context of MyProcessor.
  assert_().about(javaSource()).that(file)
      .processedWith(new MyProcessor())
      .failsToCompile()
      .withErrorContaining("some error message").in(file).onLine(5);
}

This test expects you will get some error message because @MyAnnotation is incorrectly declared in the test data source. If this assertion fails, you can run it in debug mode in your IDE, set breakpoints in MyProcessor, and step through with a full compiler environment active during debugging.

For unit testing specific methods within your processor, you can also use the @Rule called CompilationRule from which you can obtain Elements and Types utility classes in order to test specific logic in your compiler in a more isolated way.

Upvotes: 7

parsifal
parsifal

Reputation: 124

You have to invoke the Java compiler from Eclipse, using a debug configuration (you'll need to create the configuration manually, from the "Debug Configurations..." menu choice.

The "correct" way to invoke the Java compiler under JDK 1.6 or above is to use the JavaCompiler interface in javax.tools, which you get from the ToolProvider (I include all the links because there's a decent amount of class/package documentation that you should read).

The "quick-and-dirty" way (that should work, but I make no guarantees) is to invoke com.sun.tools.javac.Main.main(), passing it your normal command-line arguments. To do this, you'll need tools.jar on your classpath (it's found in $JAVA_HOME/lib).

Upvotes: 5

Related Questions