Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 744
Mubin Avatar asked Sep 06 '13 09:09

Mubin


People also ask

What is an annotated type?

What Are Type Annotations? Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.

What is the use of @interface annotation?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.

What is the @override annotation used for?

@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.


2 Answers

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.

like image 151
nanofarad Avatar answered Oct 04 '22 00:10

nanofarad


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.

like image 28
Narendra Pathai Avatar answered Oct 03 '22 22:10

Narendra Pathai