Skip to content

Commit

Permalink
Do not wrap primitives in optionals
Browse files Browse the repository at this point in the history
Since a primitive will always be present with some value it
does not really make sense to wrap them in an optional.

fix issue #107
  • Loading branch information
RoanH committed Apr 10, 2024
1 parent f5e648c commit 830a0c6
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ private JMethod addBuildMethod(JDefinedClass clazz, JDefinedClass builderClass,
}
for (JFieldVar field : declaredFields) {
if (mustAssign(field)) {
if (isRequired(field)) {
if (isRequired(field) && !field.type().isPrimitive()) {
JBlock block = method.body();
JConditional conditional = block._if(field.eq(JExpr._null()));
conditional._then()._throw(JExpr._new(builderClass.owner().ref(NullPointerException.class))
Expand Down Expand Up @@ -939,6 +939,10 @@ private boolean isMap(JClass clazz) {
}

private boolean isRequired(JFieldVar field) {
if (field.type().isPrimitive()) {
return true;
}

if (getAnnotation(field.annotations(), XmlValue.class.getCanonicalName()).isPresent()) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.github.sabomichal.immutablexjc.test.misc.Model;
import com.github.sabomichal.immutablexjc.test.misc.NameExpression;
import com.github.sabomichal.immutablexjc.test.misc.Parameters;
import com.github.sabomichal.immutablexjc.test.optionalgetter.DecimalExtensionType;
import com.github.sabomichal.immutablexjc.test.optionalgetter.NoOptionalForPrimitive;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -103,9 +105,13 @@ public void testOptionalGetter() {
.getDocumentation()
.isPresent());

com.github.sabomichal.immutablexjc.test.optionalgetter.DecimalExtensionType type = new com.github.sabomichal.immutablexjc.test.optionalgetter.DecimalExtensionType(BigDecimal.valueOf(1), "s");
DecimalExtensionType type = new DecimalExtensionType(BigDecimal.valueOf(1), "s");
assertNotNull(type.getValue());
assertEquals(BigDecimal.class, type.getValue().getClass());
assertTrue(type.getUnit().isPresent());

NoOptionalForPrimitive primitive = new NoOptionalForPrimitive(1);
assertNotNull(primitive.getIndex());
assertEquals(1, primitive.getIndex());
}
}
5 changes: 5 additions & 0 deletions src/test/xsd/basic.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,9 @@
<xs:fractionDigits value="3"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="NoOptionalForPrimitive">
<xs:sequence>
<xs:element name="index" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

0 comments on commit 830a0c6

Please sign in to comment.