javapoet: Can't add modifier to any spec in Android Studio

Calling addModifiers on TypeSpec results in can't resolve method error. After looking at source code, I have found that javax.lang.model.element.Modifier is not imported in source files. I am attaching a also attaching a snapshot, please have a look. capture

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 19 (4 by maintainers)

Most upvoted comments

Fixed this by using annotationProcessor project(path: ‘processor’) instead of compile

I found a temporary quick fix, if anyone needs it, I’ll just leave it here. So, the problem is that basically (among others) JSR 308 is missing, thus we need to support it to the compiler somehow. I found a lib that contains it, so you just have to add the following line to your dependencies in build.gradle:

compile 'org.checkerframework:checker:2.1.10'

This will fix the addModifiers(...) method, however, javaFile.writeTo(filer) still causes an annotation processor failure (at least I use it there), but that’s not a big problem since it can be avoided by manually providing the writer to that method:

JavaFileObject source = processingEnv.getFiler().createSourceFile("some.package.HelloWorld");
Writer writer = source.openWriter();
// ...
JavaFile javaFile = JavaFile.builder("some.package", helloWorld).build();
javaFile.writeTo(writer);
writer.flush();
writer.close();

This way I was able to generate the given source file with the specified modifiers.

P.S.: The Android Studio bug has been reported: https://issuetracker.google.com/issues/37358824

So what’s the solution for this bug? The file write won’t happen unless the errors are fixed. It even kills other annotation processors. annotationProcessor project(path: 'processor') won’t fix it (don’t understand why would it, it has nothing to do with the Java library module). Android Studio 2.3.1, Java 1.7 source and target compatibility.

It’s a java module and I can import javax.lang.model.element.Modifier.