All you have to do in MyAnnotationProcessor.java is:
ClassLoader cl = MyAnnotationProcessor.class.getClassLoader();
This is assuming that you’ve done an import of MyAnnotationProcessor somewhere in your Gradle script. That forces Gradle to load your class. Since all classes know what classloader loaded them, it’s easy to get it. The real trick is passing that classloader to an instance of a JavaCompiler.
Get an instance of a JavaCompiler (http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html) using ToolProvider (http://docs.oracle.com/javase/6/docs/api/javax/tools/ToolProvider.html), and get an instance of a StandardJavaFileManager (http://docs.oracle.com/javase/6/docs/api/javax/tools/StandardJavaFileManager.html) from the JavaCompiler. Passing nulls to getStandardFileManager() works for me.
Create your own implementation of StandardJavaFileManager. Let’s call it MyFileManager, and delegate all of the methods (except getClassLoader(), this is the key) to the StandardJavaFileManager you have obtained. Return the MyAnnotationProcessor classloader from the getClassLoader() method of MyFileManager. You can pass the classloader however you wish to MyFileManager. You can even have your annotation processor implement StandardJavaFileManager since it’s an interface.
When you do a getTask() using the JavaCompiler pass along your instance of MyFileManager. Now when the JavaCompiler requests a classloader from MyFileManager it will get the classloader that has already loaded MyAnnotationProcessor. Now your Gradle script and JavaCompiler have the exact same MyAnnotationProcessor class.
Note that you’ll have to pass the classpaths of all of the compilation dependencies to your JavaCompiler or else it will fail to process your source files. From your Gradle script you can use
to get all of the classpaths necessary for compilation. Remember to pass “-proc:only” to the compiler or you’ll get a bunch of unwanted .class files. You will also have to manage any compilation errors that occur during processing.
If someone can think of a better solution that would be quite nifty. Or maybe the Gradle devs could make this a built-in feature of Gradle nudge nudge wink wink.