Luis Eduardo Brito Luis Eduardo Brito - 2 months ago 8
Android Question

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?

Answer

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.