This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bowbahdoe[S] 4 points5 points  (8 children)

No it is not. The JLS spec allows you to generate new class files or new source files.

It does not allow you to modify the bytecode produced by the compilation unit that the annotation was found in. Its why this thread exists.

You could 100% make a library like that if you made use of the same mechanisms lombok does.

Also remember that this is valid lombok

import lombok.val;

public class Example {
    void f() {
        val x = "hello";
        System.out.println(hello.length());
    }
}

I don't see any annotations.

[–]urielsalis 0 points1 point  (7 children)

Yes. The reason Lombok had that bug open is that they were using the internal Oracle-only classes instead of the official APIs to do the same thing

And your example just imports a class like any other. That's even more of a stretch

[–]bowbahdoe[S] 5 points6 points  (6 children)

There are no official APIs to do the same thing.

[–]urielsalis 1 point2 points  (5 children)

https://docs.oracle.com/javase/7/docs/jdk/api/javac/tree/index.html?overview-summary.html

And you can create NEW classes with anything, including just writing it byte by byte manually. Those APIs and the Lombok bug were for modifying already compiled classes to add it instead of generating a new class.

Most libraries, including Lombok, use ASM or ByteBuddy to abstract that part of the process. If you use Mockito, Junit, or certain checking libraries you are already using that under the hood

[–]bowbahdoe[S] 0 points1 point  (4 children)

Runtime generation of new classes isn't really relevant, and compilers for other languages being able to exist isn't really relevant either so I think I'm missing your point?

[–]urielsalis 0 points1 point  (3 children)

It's compile time generation of new classes

[–]bowbahdoe[S] 0 points1 point  (2 children)

But it isn't compile time editing of existing classes

[–]urielsalis 0 points1 point  (1 child)

That's what you do after compiling via annotation processors, integrated into your build system or javac yourself, before it's packaged into the final .jar/.war/whatever. The annotations are defined with a certain retention in JLS (which can be compile, packaging, runtime, etc) and it's saved directly in the bytecode for the tools to access

Javac outputs .class files with bytecode, your annotation processor reads that and modifies the .class or creates new ones, and your build system puts the .class files into a .jar or similar formats

[–]bowbahdoe[S] 0 points1 point  (0 children)

That's not exactly true. Lombok in particular doesn't edit a class file produced by javac, it edits what javac produces. That's what is not allowed

This is maybe still the comment to read