10

How do I write a Java inner class with custom properties at compile time using annotations?

For instance, I want this :

@Generate
class Person {
     String firstname, lastname;
}

to generate:

class Person {
    String firstname, lastname;

    public static class $Fields { 
           public static String firstname = "firstname";
           public static String lastname  = "lastname";
    } 
}

How can I write the interface:

@Retention(RetentionPolicy.SOURCE)
public @interface Generate {
     // ... 
}

I understand I need to do some kind of AST transformation to make this magical.

I am also aware of project lombok, but I want to know what the least common denominator is with a simple example, preferably within one method, and preferably something that a good editor would consider automatically, for instance RetentionPolicy.SOURCE for the javac compiler, which can be used in Intellij IDEA.

Project lombok is a beast code wise and is tough place to start.

It must be simpler than that, is it not?

Any ideas?

11
  • 2
    I have a feeling it's not possible, but it would be cool if it were :)
    – user3458
    Commented Sep 23, 2014 at 20:20
  • 4
    Annotation processors would be a good place to start looking - they're in the javax.annotation.processing package.
    – Makoto
    Commented Sep 23, 2014 at 20:26
  • You can modify the generated bytecode with javassist
    – dieend
    Commented Sep 23, 2014 at 20:29
  • I think it might be possible! I found this just now : notatube.blogspot.com/2010/12/…, which is pretty condensed info. Unsure if javac compiler used with Intellij will work automagically. I will try tomorrow and hopefully get back with an answer.
    – mjs
    Commented Sep 23, 2014 at 20:31
  • 1
    Have you considered using Scala macros? (Scala is a JVM language that has full interoperability with Java that also works with IntelliJ IDEA.) This may be a bit of a steep learning curve for you, but you can do all kinds of powerful compile-time operations with them...
    – Mike Allen
    Commented Sep 23, 2014 at 20:50

1 Answer 1

3

You can do this by reflection, but your new class won't be an inner class; but be warned, you will lose static type safety.

It can be done in 2 steps:

  1. Read the annotated class via reflection and transform it into a String which represents the source code of your new class.
  2. Write this string to file, compile this String using the Java compiler API and then load and instantiate the new class, all programatically; see exact steps here.

Alternatives to achieving similar functionality can also be obtained by bytecode instrumentation (see cglib or javassist) or maybe even with proxies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.