I need your support and thanks for your Java/Annotations support..
I would to create a custom annotation f.e. @ModifyRegex to annotatate variables and my approach is to modify/replace parts of the value of the annotated variables.
f.e.
@ModifyRegex
private String variable;
if:
variable = "AbC-ABG-kkkk-4711";
then:
variable = "ABC-4711-ABG-kkkk";
I am not sure if its possible or not, if yes please provide me a simple code example..
Thanks
Annotation processors can make new source files. They cannot change existing ones. They also cannot read inside methods. They can't read any code, in fact, so the only string literal that you could possibly see is if it's literally (heh) a literal. The java lang spec defines when the value assigned to a field is considered 'compile time constant' and is written straight in. If it's not, say:
class Example {
// these are all NOT constant, therefore, cannot be
// retrieved with an annotation processor
long x = System.currentTimeMillis();
Pattern p = Pattern.compile("^AbC-ABG-$");
String s = null; // null is considered non-constant, for some reason.
String z = "HELLO!".toLowerCase();
}
But, if it's truly simple, such as @Foo private String x = "Hello";
where x
is a field (and not a local variable in a method someplace), yes, you can see it in action.
But all you can do, is make new files. You can't change an existing file. So, at best, you can make a second class that contains public static final String variable2 = "ABC-4711-...";
.
Project Lombok does everything I just said you can't do: It inspects actual code, and modifies source files in-flight.
Unfortunately, lombok is a few hundred thousand lines of code and most of it is neccessary to do all this: There is no uniform way to do it, so it's a ton of custom code. More to the point, it is also fundamentally extremely complicated: IDEs do code analysis all the time, and if you change structures, that has an effect on everything from 'auto-format my file as it is saved' to refactor scripts, to 'find callers', and so much more. Because there is no standard, you have to patch the editors to figure it out.
Changing a string constant may mean you don't need as much patching. Then it's still incredibly complicated.
Lombok is open source if you want to investigate.
NB: I'm a core contributor to Project Lombok.