简体   繁体   中英

How can I specify the type of the field that an Annotation should be applied to in Java?

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 "";
}

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.

You cannot do this using just the @Target meta-annotation. In addition, 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.

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.

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