3.14 Bean Introspection
Since Micronaut 1.1, a compilation time replacement for the JDK’s Introspector class has been included.
The BeanIntrospector and BeanIntrospection interfaces allow looking up bean introspections that allow you to instantiate and read/write bean properties without using reflection or caching reflective metadata which consumes excessive memory for large beans.
Making a Bean Available for Introspection
Unlike the JDK’s Introspector every class is not automatically available for introspection, to make a class available for introspection you must as a minimum enable Micronaut’s annotation processor (micronaut-inject-java
for Java and Kotlin and micronaut-inject-groovy
for Groovy) in your build and ensure you have a runtime time dependency on micronaut-core
.
annotationProcessor("io.micronaut:micronaut-inject-java:2.1.0")
<annotationProcessorPaths>
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-inject-java</artifactId>
<version>2.1.0</version>
</path>
</annotationProcessorPaths>
For Kotlin the micronaut-inject-java dependency should be in kapt scope and for Groovy you should have micronaut-inject-groovy in compileOnly scope. |
runtime("io.micronaut:micronaut-core:2.1.0")
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-core</artifactId>
<version>2.1.0</version>
<scope>runtime</scope>
</dependency>
Once your build is configured you have a few ways to generate introspection data.
Use the @Introspected
Annotation
The @Introspected annotation can be used on any class which you want to make available for introspection, simply annotate the class with @Introspected:
import io.micronaut.core.annotation.Introspected;
@Introspected
public class Person {
private String name;
private int age = 18;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import groovy.transform.Canonical
import io.micronaut.core.annotation.Introspected
@Introspected
@Canonical
class Person {
String name
int age = 18
Person(String name) {
this.name = name
}
}
import io.micronaut.core.annotation.Introspected
@Introspected
data class Person(var name : String) {
var age : Int = 18
}
Once introspection data has been produced at compilation time you can then retrieve it via the BeanIntrospection API:
final BeanIntrospection<Person> introspection = BeanIntrospection.getIntrospection(Person.class); (1)
Person person = introspection.instantiate("John"); (2)
System.out.println("Hello " + person.getName());
final BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String.class); (3)
property.set(person, "Fred"); (4)
String name = property.get(person); (5)
System.out.println("Hello " + person.getName());
def introspection = BeanIntrospection.getIntrospection(Person) (1)
Person person = introspection.instantiate("John") (2)
println("Hello ${person.name}")
BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String) (3)
property.set(person, "Fred") (4)
String name = property.get(person) (5)
println("Hello ${person.name}")
val introspection = BeanIntrospection.getIntrospection(Person::class.java) (1)
val person : Person = introspection.instantiate("John") (2)
print("Hello ${person.name}")
val property : BeanProperty<Person, String> = introspection.getRequiredProperty("name", String::class.java) (3)
property.set(person, "Fred") (4)
val name = property.get(person) (5)
print("Hello ${person.name}")
1 | You can retrieve a BeanIntrospection with the getIntrospection static method |
2 | Once you have a BeanIntrospection you can instantiate a bean with the instantiate method. |
3 | A BeanProperty can be retreived from the introspection |
4 | .. and the set method used to set the property value |
5 | .. and the get method used to retrieve the property value |
Constructor Methods
For classes with multiple constructors, it is possible to inform Micronaut which constructor should be used to instantiate the class. Apply the @Creator annotation to which constructor to be used.
import io.micronaut.core.annotation.Creator;
import io.micronaut.core.annotation.Introspected;
import javax.annotation.concurrent.Immutable;
@Introspected
@Immutable
public class Vehicle {
private final String make;
private final String model;
private final int axels;
public Vehicle(String make, String model) {
this(make, model, 2);
}
@Creator (1)
public Vehicle(String make, String model, int axels) {
this.make = make;
this.model = model;
this.axels = axels;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getAxels() {
return axels;
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Vehicle {
private final String make
private final String model
private final int axels
Vehicle(String make, String model) {
this(make, model, 2)
}
@Creator (1)
Vehicle(String make, String model, int axels) {
this.make = make
this.model = model
this.axels = axels
}
String getMake() {
make
}
String getModel() {
model
}
int getAxels() {
axels
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Vehicle @Creator constructor(val make: String, val model: String, val axels: Int) { (1)
constructor(make: String, model: String) : this(make, model, 2) {}
}
1 | The @Creator annotation is used to denote which constructor should be used |
This class has no default constructor so calls to instantiate without arguments will throw an InstantiationException. |
Static Creator Methods
For the use case of static methods being used to instantiate the class, the @Creator annotation can be applied to those methods to allow for the introspection to execute the method.
import io.micronaut.core.annotation.Creator;
import io.micronaut.core.annotation.Introspected;
import javax.annotation.concurrent.Immutable;
@Introspected
@Immutable
public class Business {
private String name;
private Business(String name) {
this.name = name;
}
@Creator (1)
public static Business forName(String name) {
return new Business(name);
}
public String getName() {
return name;
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Business {
private String name
private Business(String name) {
this.name = name
}
@Creator (1)
static Business forName(String name) {
new Business(name)
}
String getName() {
name
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Business private constructor(val name: String) {
companion object {
@Creator (1)
fun forName(name: String): Business {
return Business(name)
}
}
}
1 | The @Creator annotation is applied to the static method which will be used to instantiate the class |
There can be multiple “creator” methods annotated. If one exists without arguments, that will be used as the default construction method. The first method with arguments will be used as the primary construction method. |
Enums
It is possible to introspect enums as well. Simply add the annotation to the enum and it can be constructed through the standard valueOf
method.
Use the @Introspected
Annotation on a Configuration Class
If the class you wish to introspect is already compiled and not under your control an alternative option is to define a configuration class with the classes
member of the @Introspected annotation set.
import io.micronaut.core.annotation.Introspected;
@Introspected(classes = Person.class)
public class PersonConfiguration {
}
import io.micronaut.core.annotation.Introspected
@Introspected(classes = Person)
class PersonConfiguration {
}
import io.micronaut.core.annotation.Introspected
@Introspected(classes = [Person::class])
class PersonConfiguration
In the above example the PersonConfiguration
class will generate introspections for the Person
class.
You can also use the packages member of the @Introspected which will package scan at compilation time and generate introspections for all classes within a package. Note however this feature is currently regarded as experimental. |
Write an AnnotationMapper
to Introspect Existing Annotations
If there is an existing annotation that you wish to introspect by default you can write an AnnotationMapper.
An example of this is EntityIntrospectedAnnotationMapper which ensures all beans annotated with javax.persistence.Entity
are introspectable by default.
The AnnotationMapper should be on the annotation processor classpath. |
The BeanWrapper API
A BeanProperty provides raw access to read and write a property value for a given class and does not provide any automatic type conversion.
It is expected that the values you pass to the set
and get
methods match the underlying property type otherwise an exception will occur.
To provide additional type conversion smarts the BeanWrapper interface allows wrapping an existing bean instance and setting and getting properties from the bean, plus performing type conversion as necessary.
final BeanWrapper<Person> wrapper = BeanWrapper.getWrapper(new Person("Fred")); (1)
wrapper.setProperty("age", "20"); (2)
int newAge = wrapper.getRequiredProperty("age", int.class); (3)
System.out.println("Person's age now " + newAge);
final BeanWrapper<Person> wrapper = BeanWrapper.getWrapper(new Person("Fred")) (1)
wrapper.setProperty("age", "20") (2)
int newAge = wrapper.getRequiredProperty("age", Integer) (3)
println("Person's age now $newAge")
val wrapper = BeanWrapper.getWrapper(Person("Fred")) (1)
wrapper.setProperty("age", "20") (2)
val newAge = wrapper.getRequiredProperty("age", Int::class.java) (3)
println("Person's age now $newAge")
1 | The getWrapper static method can be used to obtain a BeanWrapper for a bean instance. |
2 | You can set properties and the BeanWrapper will perform type conversion, or throw ConversionErrorException if conversion is not possible. |
3 | You can retrieve a property using getRequiredProperty and request the appropriate type. If the property doesn’t exist a IntrospectionException will be thrown and if it cannot be converted a ConversionErrorException will be thrown. |
Jackson and Bean Introspection
Jackson is configured to use the BeanIntrospection API to read and write property values and construct objects resulting in reflection-free serialization/deserialization which is benefitial from a performance perspective and requires less configuring to operate correctly with runtimes such as GraalVM native.
This feature is enabled by default, you can disable it by setting the jackson.bean-introspection-module
configuration to false
.
Currently only bean properties (private field with public getter/setter) are supported and usage of public fields is not supported. |
This feature is currently regarded as experimental and may be subject to changes in the future. |