Home > Software design >  Package does not exists, generated java file from annoation processor
Package does not exists, generated java file from annoation processor

Time:09-22

I am trying to generate class using (my custom) annotation processor. (I am using spring-boot, maven ) For example

@Matcher
public class A{...}

should generate

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class AMatcher extends TypeSafeMatcher<A>{...}

However when i generate the file, it fails on package org.hamcrest does not exist error.

Since annotation processor runs first, my first guess would be that the classPath is not set so it cannot find the package.

However I'm not very experienced in using annotation processor so im not sure if this is the case.

What could cause the error, and what is the legit way how to fix this? ( If its possible )

Structure for file

src
 main
  java
   com
    testProject
     util
      A.java

Structure for generatedfile

target
 generated-sources
  annotations
   com
    testProject
     util
      AMatcher.java

Thanks for help!

CodePudding user response:

my first guess would be that the classPath is not set so it cannot find the package.

Not what's going on.

An annotation processor just kicks out a text file. At 'creation time', i.e. when the annotation processor makes this file, it's just a text file; it is not parsed, at all, as source file, and consequently, it is not possible for classpath anything to apply to that file at this phase.

Because that processor made files, the compiler realizes that new source files now exist, so it starts compilation all over again (but somewhat intelligently, not neccessarily re-processing all files) - this is the 'rounds' system, and what RoundEnv is all about in an annotation processor. It's even perfectly fine for files in the 'first' compilation run to make no sense until some APs made files, in which case those first files are compiled in the second round. In other words, javac will even defer errors of the 'not found' nature, such as the very error you got, until processing is over.

The classpath applied for any round is no different, and is the full compilation classpath.

Thus, the most likely explanation is that hamcrest (or junit) isn't on the classpath at all. Possibly you have just the junit jar on the path, and don't have the transient deps of junit (which is org.hamcrest here).

A good next step is to forget about the annotation for a moment and write the file that your AP makes as actual non-generated source file (just for now, to test and solve this issue), and you'll find you get the same error, thus showing it's not AP-related. Even if you take the entire AP off the path / disable AP processing at that point.

  • Related