Skip to main content

@NameProperty Annotation

The @NameProperty annotation is used to identify a setter method or field for setting the name of a POJO as it's known by its parent object.

This annotation is used by parsers to automatically set the name/key of an object when parsing structured data (e.g., JSON maps, XML elements). A common use case is when parsing a map where the map key should be stored as a property on the bean.

Requirements

  • Must be an instance method or field (not static)
  • For methods: Must accept exactly one parameter (any type)
  • For fields: Can be any type
  • The method or field does not need to be public (will be made accessible automatically)

Usage

Can be applied to:

  • Bean setter methods or fields
  • @Rest-annotated classes and @RestOp-annotated methods when using the on() parameter

Example

Using a Field

// JSON being parsed:
{
"id1": {name: "John Smith", sex: "M"},
"id2": {name: "Jane Doe", sex: "F"}
}
public class Person {
@NameProperty
public String id; // Gets set to "id1" or "id2" from map key

public String name;
public char sex;
}

Using a Setter Method

public class Person {
private String id;

@NameProperty
protected void setName(String name) {
this.id = name;
}

public String name;
public char sex;
}

When It's Called

  • During parsing when an object is created as a value in a map/collection
  • The parser automatically calls the setter or sets the field with the key/name from the parent structure
  • This allows the bean to know its key/name within the parent container
Discussion

Share feedback or follow-up questions for this page directly through GitHub.