简体   繁体   中英

Can you generate code the overrides a method using Java annotations?

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM