我怎么可以指定一个注释应该在的Java应用到字段的类型? [英] How can I specify the type of the field that an Annotation should be applied to in Java?
问题描述
我要创建一个简单的注解,帮我膨胀在我的Android应用程序的设置。注释是这样的:
I'm creating a simple annotation, to help me inflating settings inside my Android application. The annotation is this:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CoreSettings {
String name() default "";
}
我要确保它只会在哪种类型的扩展名为 BaseSettings自定义类领域。在下面的例子中,MainSettings扩展抽象类BaseSettings
I want to ensure it will only be used in fields which type extends a custom class named BaseSettings. In the example below, MainSettings extends the abstract class BaseSettings.
public class MainActivity extends BaseActivity {
@CoreSettings("prefs")
MainSettings settings;
(...)
}
我该怎么办呢?
How can I do it?
推荐答案
是的,你可以让编译器,如果你写在错误类型的字段注释发出错误信息。
Yes, you can cause the compiler to issue an error message if you write the annotation on a field of the wrong type.
您不能只使用了 @Target
元注解做到这一点。相反,你需要编写一个注解处理器。注解处理器会检查你的源$ C $ c中的注释 @CoreSettings
的每一次出现,如果<$ C则发出错误(就像任何其他的编译器错误) $ C> @CoreSettings 适用于一个类型,没有延伸 BaseSettings
。这是一个简短的注释处理器来写。
You cannot do this using just the @Target
meta-annotation. Instead, you need to write an annotation processor. The annotation processor will examine each occurrence of the annotation @CoreSettings
in your source code, and it issues an error (just like any other compiler error) if @CoreSettings
is applied to a type that does not extend BaseSettings
. This is a short, simple annotation processor to write.
运行批注处理器时,你将只能得到编译时警告,但你可以添加 -processor ...
命令行参数在您的项目的给javac构建文件。
You will only get the compile-time warning when running the annotation processor, but you can add the -processor ...
command-line argument to javac in your project's buildfile.
这篇关于我怎么可以指定一个注释应该在的Java应用到字段的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!