Reputation: 71
Is it possible to write a Java annotation for a class that generates a method that overrides the class's parent method?
In my case I want to do it in android:
@OverrideOnTouch
class Foo extends Activity {
And it will generate an onTouch override method in compile time.
Is it possible?
Upvotes: 0
Views: 1233
Reputation: 719386
An annotation cannot generate code.
You could write an annotation processor that added a method at compile time wherever it found your annotation.
Here is a tutorial on this subject:
However, beware that writing an annotation processor is a significant amount of Java coding work. Also note that an annotation processor (implemented using the AnnotationProcessor
API and called via the Java compiler) cannot modify Java source code. It can only generate new ".java" files.
So, if you want to inject new method into an existing class, you would need to compile the class, and then use a post-compilation annotation processor that used BCEL or equivalent to add the required methods to the ".class" files produced by the compiler. Implementing a BCEL-based processor is ... even harder. And such processors have a tendency to break when you upgrade Java. (It is easy to make assumptions about the JVM / bytecode level implementation that are not supported by the relevant specs ... and no longer "work" when the platform changes.)
This approach is mentioned in some of the answers to this Question:
Upvotes: 4