0

I have an interface like this

@MyAnnotation
public interface Foo {
    public String methodA();
    public String methodB();
}

I'd like, at compilation time, to add some constant filed to this interface without modifying the source code

@MyAnnotation
public interface Foo {
    static final String METHOD_A = "methodA";
    static final String METHOD_B = "methodB";

    String methodA();
    String methodB();
}

so in the code I can use Foo.METHOD_A event though the constant is not defined (like Lombok)

I've foude some examples using AnnotationProcessors (https://gist.github.com/pietrocaselani/8624554 or https://github.com/sockeqwe/annotationprocessing101) but they seem to use com.sun.tools.javac that is for java8 and i dont seem to find an alternative for java11

lelmarir
  • 593
  • 2
  • 7
  • 24
  • Are you looking for something like https://stackoverflow.com/questions/40850926/nameof-equivalent-in-java? – Progman Jul 07 '23 at 17:06
  • To transform class files you can use [https://asm.ow2.io/](https://asm.ow2.io/) or wait for the [Class-File API](https://openjdk.org/jeps/8280389) to reach preview status. – Alex R Jul 07 '23 at 17:36
  • 1
    The `java.compiler` / `jdk.compiler` modules don't provide an API to do this. What you want to do is similar to what Lombok does, and that library does this by "hacking" into the internals of javac and ECJ (each compiler requires a different implementation, if you want to support each of them). Maybe you can extend Lombok (not sure). At the very least, you can see how Lombok is implemented: https://github.com/projectlombok/lombok – Slaw Jul 07 '23 at 19:27

0 Answers0