@BeanCtor Annotation
The @BeanCtor annotation is applied to bean constructors to map constructor arguments to property names on beans with read-only properties.
Since method parameter names are lost during compilation, this annotation essentially redefines them so that they are available at runtime and the framework can instantiate read-only beans during parsing.
This annotation lives in juneau-commons so the bean-modeling layer can describe constructor argument
mappings without depending on the marshalling layer.
This annotation was previously named @Beanc. Usages of @Beanc should be updated to @BeanCtor
(in org.apache.juneau.commons.bean). This annotation can only be applied to constructors, and only one
constructor per class may carry it.
Basic Usage: properties
The definition of a read-only bean is a bean with properties with only getters, like shown below:
// Our read-only bean.
public class Person {
private final String name;
private final int age;
@BeanCtor(properties="name,age")
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Read only properties.
// Getters but no setters.
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// Parsing into a read-only bean.
String json = "{name:'John Smith',age:45}";
Person person = Json.to(json, Person.class);
String name = person.getName(); // "John Smith"
int age = person.getAge(); // 45
Beans can also be defined with a combination of read-only and read-write properties.
Using @Name Instead
The @Name annotation can also
be used instead of @BeanCtor(properties) to label individual parameters:
@BeanCtor
public Person(@Name("name") String name, @Name("age") int age) {
this.name = name;
this.age = age;
}
If neither @BeanCtor(properties) nor @Name is used to identify the bean property names, the framework
will try to use the parameter names if they are available in the bytecode.
Java Records
For Java records, the canonical constructor and its property mappings are automatically detected, so this annotation is not required. It can still be used to specify a non-canonical constructor if needed, for example to provide default values for certain components:
@BeanType(properties="name")
public record WithBeanCtor(String name, int age) {
@BeanCtor(properties="name")
public WithBeanCtor(String name) {
this(name, 0); // Default age to 0
}
}
When using @BeanCtor with a non-canonical constructor on a record, use
@BeanType(properties)
to limit the visible properties to match the constructor parameters.
- @BeanType Annotation - Class-level bean-modeling annotation.
- @BeanProp Annotation - Property-level bean-modeling annotation.
- Java Records Support - Full documentation on Java records support.