Java reflection get annotation parameters

Java Reflection — Annotations

Using Java Reflection you can access the annotations attached to Java classes at runtime.

What are Java Annotations?

Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. Here is an example of class annotation:

@MyAnnotation(name=»someName», value = «Hello World») public class TheClass

The class TheClass has the annotation @MyAnnotation written ontop. Annotations are defined like interfaces. Here is the MyAnnotation definition:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotation

The @ in front of the interface marks it as an annotation. Once you have defined the annotation you can use it in your code, as shown in the earlier examples.

The two directives in the annotation definition, @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE) , specifies how the annotation is to be used.

@Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. If you do not set this directive, the annotation will not be preserved at runtime, and thus not available via reflection.

@Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces typically). You can also specify METHOD or FIELD , or you can leave the target out alltogether so the annotation can be used for both classes, methods and fields.

Java annotations are explained in more detail in my Java Annotations tutorial.

Class Annotations

You can access the annotations of a class, method or field at runtime. Here is an example that accesses the class annotations:

Class aClass = TheClass.class; Annotation[] annotations = aClass.getAnnotations(); for(Annotation annotation : annotations) < if(annotation instanceof MyAnnotation)< MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); >>

You can also access a specific class annotation like this:

Class aClass = TheClass.class; Annotation annotation = aClass.getAnnotation(MyAnnotation.class); if(annotation instanceof MyAnnotation)

Method Annotations

Here is an example of a method with annotations:

You can access method annotations like this:

Method method = . //obtain method object Annotation[] annotations = method.getDeclaredAnnotations(); for(Annotation annotation : annotations) < if(annotation instanceof MyAnnotation)< MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); >>

You can also access a specific method annotation like this:

Method method = . // obtain method object Annotation annotation = method.getAnnotation(MyAnnotation.class); if(annotation instanceof MyAnnotation)

Parameter Annotations

It is possible to add annotations to method parameter declarations too. Here is how that looks:

Читайте также:  Java net connectexception connection timed out no further information radmin vpn

You can access parameter annotations from the Method object like this:

Method method = . //obtain method object Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Class[] parameterTypes = method.getParameterTypes(); int i=0; for(Annotation[] annotations : parameterAnnotations) < Class parameterType = parameterTypes[i++]; for(Annotation annotation : annotations)< if(annotation instanceof MyAnnotation)< MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("param: " + parameterType.getName()); System.out.println("name : " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); >> >

Notice how the Method.getParameterAnnotations() method returns a two-dimensional Annotation array, containing an array of annotations for each method parameter.

Field Annotations

Here is an example of a field with annotations:

You can access field annotations like this:

Field field = . //obtain field object Annotation[] annotations = field.getDeclaredAnnotations(); for(Annotation annotation : annotations) < if(annotation instanceof MyAnnotation)< MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); >>

You can also access a specific field annotation like this:

Field field = . // obtain method object Annotation annotation = field.getAnnotation(MyAnnotation.class); if(annotation instanceof MyAnnotation)

Источник

Method Class | getParameterAnnotations() method in Java

The java.lang.reflect.Method.getParameterAnnotations() method of Method class returns a two-dimensional Annotation array, that represents the annotations on the parameters, of the Method object. If the Method contains no parameters, an empty array will be returned. If the Method contains one or more parameters then a two-dimension Annotation array will be returned. A nested array of this two-dimension array will be empty for the parameter with no annotations. At the time of compilation mandated and synthetic parameters are added to the array. Mandated parameter are parameters which implicitly declared in source and Synthetic parameter are parameters that are neither implicitly nor explicitly declared in the source. The objects of annotation returned by this method are serializable. The array of arrays returned by this method can be easily modified.

public Annotation[][] getParameterAnnotations()

Return Value: This method returns a two-dimensional Annotation array, that represent the annotations on the formal and implicit parameters, of the Method object. Below programs illustrates getParameterAnnotations() method of Method class:

Example 1: To use getParameterAnnotations() for a Specific Method given as Input. The program contains a Method name setManyValues() which contains parameter Annotations. So this program is going to get all parameter Annotations contain by setManyValues() Method.

Источник

Changing Annotation Parameters at Runtime

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

Читайте также:  Sort numbers in string java

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

Annotations , a form of metadata which you can add to Java code. These annotations can be processed at compile time and embedded to class files or can be retained and accessed at runtime using Reflection .

In this article, we will discuss how to change annotation value at runtime using Reflection. We will use class-level annotation for this example.

2. Annotation

Java allows creating new annotations using existing ones. In the simplest form, an annotation is represented as @ symbol followed by annotation name:

Let’s create our own annotation Greeter:

@Retention(RetentionPolicy.RUNTIME) public @interface Greeter

Now, we will be creating a Java class Greetings which uses the class-level annotation :

@Greeter(greet="Good morning") public class Greetings <> 

Now, we will access annotation value using reflection. Java class Class provides a method getAnnotation to access annotations of a class:

Greeter greetings = Greetings.class.getAnnotation(Greeter.class); System.out.println("Hello there, " + greetings.greet() + " !!");

3. Alter Annotation

Java class Class maintains a map for managing annotations – Annotation class as keys and Annotation object as value:

We will update this map to alter annotation at runtime. Approach to access this map differs in various JDK implementation. We will discuss it for JDK7 and JDK8.

Читайте также:  Изменение атрибутов элемента javascript

3.1. JDK 7 Implementation

Java class Class has field annotations. As this is a private field, to access it, we have to set accessibility of the field to true. Java provides method getDeclaredField to access any field by its name:

Field annotations = Class.class.getDeclaredField(ANNOTATIONS); annotations.setAccessible(true); 

Now, let’s get access to annotation map for class Greeter:

 Map, Annotation> map = annotations.get(targetClass);

Now, this is the map which contains information about all annotations and their value object. We want to alter Greeter annotation value which we can achieve by updating annotation object of Greeter class:

map.put(targetAnnotation, targetValue);

3.2. JDK 8 Implementation

Java 8 implementations stores annotations information inside a class AnnotationData . We can access this object using the annotationData method. We will set accessibility for the annotationData method to true as it is a private method:

Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null); method.setAccessible(true);

Now, we can access annotations field. As this field also a private field, we will set accessibility to true:

Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS); annotations.setAccessible(true);

This field has annotations cache map which stores annotation class and value object. Let’s alter that:

Map, Annotation> map = annotations.get(annotationData); map.put(targetAnnotation, targetValue);

4. Application

Greeter greetings = Greetings.class.getAnnotation(Greeter.class); System.err.println("Hello there, " + greetings.greet() + " !!");

This will be greeting “Good morning” as that is the value we provided to annotation.
Now, we will create one more object of Greeter type with value as “Good evening”:

Greeter targetValue = new DynamicGreeter("Good evening"); 

Let’s update the annotation map with the new value:

alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);

Let’s check greeting value again:

greetings = Greetings.class.getAnnotation(Greeter.class); System.err.println("Hello there, " + greetings.greet() + " !!");

It will greet as “Good evening”.

5. Conclusion

Java implementations use two data field to store annotation data: annotations, declaredAnnotations. The difference between these two: first store annotations from parent classes also and later one stores only for current class.

As the implementation of getAnnotation differs in JDK 7 and JDK 8, we using here annotations field map for simplicity.

And, as always, the source code of implementation is available over on Github.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью