我需要能够使用注释来控制 Java Map 的大小(条目数)。
以下内容适用于 Java 列表,但不适用于地图:
@XmlElement
@Size(max = 2)
public List<Mytype> getMytypes() { return mytypes; }
@XmlElement
@Size(max = 2)
public Map<MyothertypeEnum, Myothertype> getMyothertypes() { return myothertypes; }
生成的模式(使用 JAXB)如下所示:
对于列表:
<xsd:element name="mytypes" type="ns0:Mytype" minOccurs="0" maxOccurs="2"/>
对于地图:
<xsd:element name="myothertypes" minOccurs="0" maxOccurs="2">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="entry" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="key" type="ns0:MyothertypeEnum" minOccurs="0"/>
<xsd:element name="value" type="ns0:Myothertype" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
如何编写注释以使 Map 'entry' 元素具有最大大小?我正在尝试将“@Size”注释应用于“entry”元素。
我不明白“myothertypes”元素上的 macOccurs 是什么意思。只允许使用一张地图,而不是 2 张。
预先感谢您的帮助。
@Size 控制集合的大小限制,因此它影响整个 myothertypes 映射。
maxOccurs 与元素出现的次数有关。 要控制条目数量,请使用自定义 getter 方法创建自定义验证机制,然后应用大小约束逻辑。
java 导入 javax.validation.constraints.Size; 导入 java.util.Map;
公共课你的班级{
私人地图
// Getter method with custom size validation logic
@XmlElement
public Map<MyothertypeEnum, Myothertype> getMyothertypes() {
if (myothertypes.size() > 2) {
throw new IllegalStateException("myothertypes map size exceeds maximum allowed size of 2");
}
return myothertypes;
}
// Other methods and annotations for Myothertypes
}