简体   繁体   English

您可以使用Java批注生成覆盖方法的代码吗?

[英]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? 是否可以为类编写Java注释,该注释会生成覆盖该类的父方法的方法?

In my case I want to do it in android: 就我而言,我想在android中做到这一点:

@OverrideOnTouch class Foo extends Activity {

And it will generate an onTouch override method in compile time. 它将在编译时生成一个onTouch覆盖方法。

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. 但是,请注意编写注释处理器是大量的Java编码工作。 Also note that an annotation processor (implemented using the AnnotationProcessor API and called via the Java compiler) cannot modify Java source code. 还要注意,注释处理器(使用AnnotationProcessor API实现并通过Java编译器调用)不能修改Java源代码。 It can only generate new ".java" files. 它只能生成新的“ .java”文件。

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. 因此,如果要将新方法注入到现有的类中,则需要编译该类,然后使用使用BCEL或等效方法的编译后注解处理器将所需的方法添加到由.NET生成的“ .class”文件中编译器。 Implementing a BCEL-based processor is ... even harder. 实施基于BCEL的处理器更加困难。 And such processors have a tendency to break when you upgrade Java. 而且,当您升级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.) (很容易对相关规范不支持的JVM /字节码级别实现进行假设,并且在平台更改时不再“起作用”。)

This approach is mentioned in some of the answers to this Question: 该问题的一些答案中提到了这种方法:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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