I'm considering the approaches to write
class MyClass {
@Get
@Set
protected int aValue;
}
and then, automatically, generate get_aValue() and set_AValue() methods for the class.
I've found these possibilities:
1a) At compile time. Use an annotation processor for separately processing MyClass.java, then write a new MyClass.java, and finally use this latter (substituting the original) with the rest of .java
1b) At compile time. Use an annotation processor to generate a MyClassGenerated.java file with a new class (with the get/set methods) being this one a sub-class of the original MyClass.
2) At run time. Use java.lang.instrument and an external tool (like BCEL) to weave new code in MyClass.class.
Well, the questions are: considering that as far as possible I don't want to use third party libraries (like the lombok project or BCEL)
a) Am I missing any other approach?
b) Which approach would you use?
I guess I will use 1a) because
1b) is not clean (the rest of the program should use MyClassGeneradted instead of the original MyClass, although perhaps it's only a matter of names)
2) is really difficult (for me, at least).
You are missing something, which I'd say is the best approach if you want to go down this route:
1c) At compile time. Compile the class as normal, then use an APT annotation processor to modify the .class file (not the source file) to add the appropriate get and set methods to the bytecode.
This way your source stays pristine, you don't have to faff about with temporary files, and the actual compiled class is exactly as you want it to be.
Still, this is using a sledgehammer to open a nut. It's do-able, but now your code isn't strictly Java in the sense that if someone takes it and runs javac
on it, they'll get a class without getters and setters. This will make debugging difficult as all the line numbers will be messed up, and unless you're very sure you've done the right thing with your annotation processor, you won't even be able to see the source of the getters and setters to correct mistakes. Static analysis tools will tell you that the attribute is never used, etc.
I'm with the general consensus - just generate them in the source file using the methods that every IDE gives you. This takes barely any more time than writing annotations, and is understood by every developer and tool out there. Java doesn't have properties - get over it. :-)