Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java annotation dynamic typecast

I have 2 java annotation types, let's say XA and YA. Both have some method(). I parse the source code and retrieve Annotation object. Now I'd like to dynamicaly cast the annotation to the real type of it to be able to call the method(). How can I do it without the instanceof statement? I really want to avoid switch-like source. I need something like this:

Annotation annotation = getAnnotation(); // I recieve the Annotation object here
String annotationType = annotation.annotationType().getName();

?_? myAnnotation = (Class.forName(annotationType)) annotation;
annotation.method(); // this is what I need, get the method() called

?_? means I have no idea what would be myAnnotation type. I cannot use the base class for my XA and YA annotations since the inheritance in annotations is not allowed. Or is it possible to do somehow?

Thanks for any suggestion or help.

like image 293
Pavel S. Avatar asked Apr 29 '11 13:04

Pavel S.


People also ask

What is typecasting in Java?

The process of converting the value of one data type ( int, float, double, etc.) to another data type is known as typecasting. In Java, there are 13 types of type conversion.

What are annotations in Java?

These annotations consist of multiple data members, names, values, pairs. These annotations can be applied to any place where a type is being used. For example, we can annotate the return type of a method.

What is type casting in C++?

Convert a value from one data type to another data type is known as type casting. There are two types of type casting: Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or casting down.

What is widening type casting in Java?

Here, the Java first converts the int type data into the double type. And then assign it to the double variable. In the case of Widening Type Casting, the lower data type (having smaller size) is converted into the higher data type (having larger size).


1 Answers

Why don't you use the typesafe way to retrieve your annotation ?

final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
annotation.yourMethod();

If your annotation can't be found, null is returned.

Please note that this also works with fields and methods.

like image 178
faulomi Avatar answered Sep 30 '22 22:09

faulomi