Skip to content

Support for Java 14 records (#2709) #2714

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,56 @@
<skipTests>true</skipTests>
</properties>
</profile>
<profile>
<!-- Build Record tests using Java 14 if JDK is available -->
<id>java14+</id>
<activation>
<jdk>[14,</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-test-source</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test-jdk14/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<inherited>true</inherited>
<configuration>
<optimize>true</optimize>
<!-- Enable Java 14+ for all sources so that Intellij picks the right language level -->
<release>${java.vm.specification.version}</release>
<compilerArgs>
<arg>-parameters</arg>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,14 @@ private PropertyName _findParamName(DeserializationContext ctxt,
return PropertyName.construct(str);
}
}

if (param != null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely needs javadocs to explain why is this needed.

Class<?> ownerClass = param.getOwner().getType().getRawClass();
if (RecordUtil.isRecord(ownerClass)) {
String recordComponentName = RecordUtil.getRecordComponents(ownerClass)[param.getIndex()];
return PropertyName.construct(recordComponentName);
}
}
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.RecordUtil;

/**
* Helper class used for aggregating information about all possible
Expand Down Expand Up @@ -488,7 +489,10 @@ protected void _addCreatorParam(Map<String, POJOPropertyBuilder> props,
// Also: if this occurs, there MUST be explicit annotation on creator itself
JsonCreator.Mode creatorMode = _annotationIntrospector.findCreatorAnnotation(_config,
param.getOwner());
if ((creatorMode == null) || (creatorMode == JsonCreator.Mode.DISABLED)) {
// record canonical constructor does not require annotation to be used
boolean isRecordCanonicalConstructor = RecordUtil.getCanonicalConstructor(_classDef) == param.getOwner();
if (!isRecordCanonicalConstructor
&& (creatorMode == null) || (creatorMode == JsonCreator.Mode.DISABLED)) {
return;
}
pn = PropertyName.construct(impl);
Expand Down
14 changes: 11 additions & 3 deletions src/main/java/com/fasterxml/jackson/databind/util/BeanUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.fasterxml.jackson.databind.util;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
Expand All @@ -8,6 +9,7 @@
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;


/**
* Helper class that contains functionality needed by both serialization
* and deserialization side.
Expand All @@ -31,11 +33,17 @@ public static String okNameForGetter(AnnotatedMember am) {

public static String okNameForRegularGetter(AnnotatedMember am, String name)
{
if (RecordUtil.isRecord(am.getDeclaringClass()) &&
Arrays.asList(RecordUtil.getRecordComponents(am.getDeclaringClass())).contains(name)) {
// record getters are not prefixed
return name;
}

if (name.startsWith("get")) {
/* 16-Feb-2009, tatu: To handle [JACKSON-53], need to block
* CGLib-provided method "getCallbacks". Not sure of exact
* safe criteria to get decent coverage without false matches;
* but for now let's assume there's no reason to use any
* but for now let's assume there's no reason to use any
* such getter from CGLib.
* But let's try this approach...
*/
Expand Down Expand Up @@ -79,7 +87,7 @@ public static String okNameForMutator(AnnotatedMember am, String prefix)
/* Value defaulting helpers
/**********************************************************
*/

/**
* Accessor used to find out "default value" to use for comparing values to
* serialize, to determine whether to exclude value from serialization with
Expand Down Expand Up @@ -130,7 +138,7 @@ public static Object getDefaultValue(JavaType type)

/**
* This method was added to address the need to weed out
* CGLib-injected "getCallbacks" method.
* CGLib-injected "getCallbacks" method.
* At this point caller has detected a potential getter method
* with name "getCallbacks" and we need to determine if it is
* indeed injectect by Cglib. We do this by verifying that the
Expand Down
103 changes: 103 additions & 0 deletions src/main/java/com/fasterxml/jackson/databind/util/RecordUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.fasterxml.jackson.databind.util;

import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.AnnotatedConstructor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
* Helper class to detect Java records without Java 14 as Jackson targets is Java 8.
* <p>
* See <a href="https://openjdk.java.net/jeps/359">JEP 359</a>
*/
public final class RecordUtil {

private static final Method IS_RECORD;
private static final Method GET_RECORD_COMPONENTS;
private static final Method GET_NAME;
private static final Method GET_TYPE;

static {
Method isRecord;
Method getRecordComponents;
Method getName;
Method getType;
try {
isRecord = Class.class.getDeclaredMethod("isRecord");
getRecordComponents = Class.class.getMethod("getRecordComponents");
Class c = Class.forName("java.lang.reflect.RecordComponent");
getName = c.getMethod("getName");
getType = c.getMethod("getType");
} catch (ClassNotFoundException| NoSuchMethodException e) {
// pre-Java-14
isRecord = null;
getRecordComponents = null;
getName = null;
getType = null;
}
IS_RECORD = isRecord;
GET_RECORD_COMPONENTS = getRecordComponents;
GET_NAME = getName;
GET_TYPE = getType;
}

public static boolean isRecord(Class<?> aClass) {
try {
return IS_RECORD == null ? false : (boolean) IS_RECORD.invoke(aClass);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new AssertionError();
}
}

/**
* @return Record component's names, ordering is preserved.
*/
public static String[] getRecordComponents(Class<?> aRecord) {
if (!isRecord(aRecord)) {
return new String[0];
}

try {
Object[] components = (Object[]) GET_RECORD_COMPONENTS.invoke(aRecord);
String[] names = new String[components.length];
for (int i = 0; i < components.length; i++) {
Object component = components[i];
names[i] = (String) GET_NAME.invoke(component);
}
return names;
} catch (Throwable e) {
return new String[0];
}
}

public static AnnotatedConstructor getCanonicalConstructor(AnnotatedClass aRecord) {
if (!isRecord(aRecord.getAnnotated())) {
return null;
}

Class<?>[] paramTypes = getRecordComponentTypes(aRecord.getAnnotated());
for (AnnotatedConstructor constructor : aRecord.getConstructors()) {
if (Arrays.equals(constructor.getAnnotated().getParameterTypes(), paramTypes)) {
return constructor;
}
}
return null;
}

private static Class<?>[] getRecordComponentTypes(Class<?> aRecord) {
try {
Object[] components = (Object[]) GET_RECORD_COMPONENTS.invoke(aRecord);
Class<?>[] types = new Class[components.length];
for (int i = 0; i < components.length; i++) {
Object component = components[i];
types[i] = (Class<?>) GET_TYPE.invoke(component);
}
return types;
} catch (Throwable e) {
return new Class[0];
}
}
}

105 changes: 105 additions & 0 deletions src/test-jdk14/java/com/fasterxml/jackson/databind/RecordTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.fasterxml.jackson.databind;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;

import java.io.IOException;

public class RecordTest extends BaseMapTest {

private JsonMapper jsonMapper;

public void setUp() {
jsonMapper = new JsonMapper();
}

public record SimpleRecord(int id, String name) {
}

public void testSerializeSimpleRecord() throws JsonProcessingException {
SimpleRecord record = new SimpleRecord(123, "Bob");

String json = jsonMapper.writeValueAsString(record);

assertEquals("{\"id\":123,\"name\":\"Bob\"}", json);
}

public void testDeserializeSimpleRecord() throws IOException {
SimpleRecord value = jsonMapper.readValue("{\"id\":123,\"name\":\"Bob\"}", SimpleRecord.class);

assertEquals(new SimpleRecord(123, "Bob"), value);
}

public void testSerializeSimpleRecord_DisableAnnotationIntrospector() throws JsonProcessingException {
SimpleRecord record = new SimpleRecord(123, "Bob");

JsonMapper mapper = JsonMapper.builder()
.configure(MapperFeature.USE_ANNOTATIONS, false)
.build();
String json = mapper.writeValueAsString(record);

assertEquals("{\"id\":123,\"name\":\"Bob\"}", json);
}

public void testDeserializeSimpleRecord_DisableAnnotationIntrospector() throws IOException {
JsonMapper mapper = JsonMapper.builder()
.configure(MapperFeature.USE_ANNOTATIONS, false)
.build();
SimpleRecord value = mapper.readValue("{\"id\":123,\"name\":\"Bob\"}", SimpleRecord.class);

assertEquals(new SimpleRecord(123, "Bob"), value);
}

public record RecordOfRecord(SimpleRecord record) {
}

public void testSerializeRecordOfRecord() throws JsonProcessingException {
RecordOfRecord record = new RecordOfRecord(new SimpleRecord(123, "Bob"));

String json = jsonMapper.writeValueAsString(record);

assertEquals("{\"record\":{\"id\":123,\"name\":\"Bob\"}}", json);
}

public record JsonIgnoreRecord(int id, @JsonIgnore String name) {
}

public void testSerializeJsonIgnoreRecord() throws JsonProcessingException {
JsonIgnoreRecord record = new JsonIgnoreRecord(123, "Bob");

String json = jsonMapper.writeValueAsString(record);

assertEquals("{\"id\":123}", json);
}

public record RecordWithConstructor(int id, String name) {
public RecordWithConstructor(int id) {
this(id, "name");
}
}

public void testDeserializeRecordWithConstructor() throws IOException {
RecordWithConstructor value = jsonMapper.readValue("{\"id\":123,\"name\":\"Bob\"}", RecordWithConstructor.class);

assertEquals(new RecordWithConstructor(123, "Bob"), value);
}

public record JsonPropertyRenameRecord(int id, @JsonProperty("rename")String name) {
}

public void testSerializeJsonRenameRecord() throws JsonProcessingException {
JsonPropertyRenameRecord record = new JsonPropertyRenameRecord(123, "Bob");

String json = jsonMapper.writeValueAsString(record);

assertEquals("{\"id\":123,\"rename\":\"Bob\"}", json);
}

public void testDeserializeJsonRenameRecord() throws IOException {
JsonPropertyRenameRecord value = jsonMapper.readValue("{\"id\":123,\"rename\":\"Bob\"}", JsonPropertyRenameRecord.class);

assertEquals(new JsonPropertyRenameRecord(123, "Bob"), value);
}
}
Loading