Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an annotation processor that processes a Local Variable?

I'm trying to create an annotation for a local variable. I know that I can't retain the annotation in the generated bytecode, but I should be able to have access to the information at compile time by doing something like this:

@Target({ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface Junk {
  String value();
}

only, this doesn't get processed by apt, or javac when I specify a ProcessorFactory that has "Junk" in it's supported types in the following:

class JunkTester {
    public static void main(String[] args) {
        @Junk String tmp = "Hello World";
        System.out.println(tmp);
    }
}

It will however work when I move the @Junk annotation before public static

Thoughts and or workarounds?

like image 317
apg Avatar asked Jul 19 '10 22:07

apg


People also ask

Can annotations be used on local variables?

Annotations can be applied to packages, types (classes, interfaces, enumerated types, and even annotation types), type members (methods, constructors, fields, and enumerated values), method parameters, and local variables (including loop variables and catch parameters).

What is annotation processing tool?

Annotation processing is a tool built into javac for scanning and processing annotations at compile time. It can create new source files; however, it can't modify existing ones. It's done in rounds. The first round starts when the compilation reaches the pre-compile phase.


1 Answers

Did some quick tests and searched a little, and it's looking like hooking into LOCAL_VARIABLE isn't really supported...yet:

http://forums.sun.com/thread.jspa?threadID=775449
http://www.cs.rice.edu/~mgricken/research/laptjavac/
https://checkerframework.org/jsr308/

Could be totally wrong, but that's how it's looking...

like image 91
kschneid Avatar answered Sep 22 '22 06:09

kschneid