Mubin
Mubin

Reputation: 4239

Annotation applicable to specific data type

I don't know if the question I am asking is really stupid. But here it is:

I would like to write a custom annotation which should be applicable to a specific type. For example, if I have a class A, then I would like to have an annotation that can be applied on objects of A.

Something like this:

@Target({ElementType.FIELD, //WHAT_ELSE_HERE_?})
public @interface MyAnnotation {
   String attribute1();
}

public class X {
   @MyAnnotation (attribute1="...") //SHOULDN'T BE POSSIBLE
   String str;
   @MyAnnotation (attribute1="..") //PERFECTLY VALID
   A aObj1;
   @MyAnnotation (attribute1="...") //SHOULDN'T BE POSSIBLE
   B bObj1;
}

Is that possible at all?

Upvotes: 18

Views: 13009

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 42005

That is not possible in Java.

But you have an option to write your own annotation processor if you want to check the correctness of the annotations before runtime.

Annotation processing is a hook in the compile process, to analyse the source code for user defined annotations and handle then (by producing compiler errors, compiler warning, emmiting source code, byte code ..).

A basic tutorial on Annotation Processing.

Upvotes: 7

nanofarad
nanofarad

Reputation: 41311

Not possible. @Target uses ElementType[], and ElementType is an enum, so you can't modify it. It does not contain a consideration for only specific field types.

You can, however, discard the annotation at runtime, or raise runtime exceptions about it.

Upvotes: 13

Related Questions