Skip to content

Commit

Permalink
android-record: Adapt generic types returned by Android reflection to…
Browse files Browse the repository at this point in the history
… follow Java behavior.
  • Loading branch information
HelloOO7 committed Sep 3, 2024
1 parent 862ff03 commit 032b52e
Showing 1 changed file with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.fasterxml.jackson.module.androidrecord;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.lang.reflect.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -119,7 +116,7 @@ public PotentialCreator findDefaultCreator(MapperConfig<?> config,
AnnotatedConstructor constructor = (AnnotatedConstructor) creator.creator();
Parameter[] parameters = constructor.getAnnotated().getParameters();
Map<String, Type> parameterTypes = Arrays.stream(parameters)
.collect(Collectors.toMap(Parameter::getName, Parameter::getParameterizedType));
.collect(Collectors.toMap(Parameter::getName, parameter -> fixAndroidGenericType(parameter.getParameterizedType())));

if (parameterTypes.equals(components)) {
if (foundCreator != null) {
Expand Down Expand Up @@ -150,4 +147,30 @@ static boolean isDesugaredRecordClass(Class<?> raw) {
static Stream<Field> getDesugaredRecordComponents(Class<?> raw) {
return Arrays.stream(raw.getDeclaredFields()).filter(field -> !Modifier.isStatic(field.getModifiers()));
}

static Class<?> arrayTypeCompat(Class<?> componentType) {
return Array.newInstance(componentType, 0).getClass();
}

static Type fixAndroidGenericType(Type type) {
if (type instanceof GenericArrayType) {
//recurse into component type
Type componentType = fixAndroidGenericType(((GenericArrayType) type).getGenericComponentType());
if (componentType instanceof Class<?>) { //if it isn't generic, return the raw array type
return arrayTypeCompat((Class<?>) componentType);
}
}
else if (type instanceof ParameterizedType) {
//if the parameterized type is not actually parameterized, deduce the raw type
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class<?>) {
Class<?> rawComponentClass = (Class<?>) rawType;
if (rawComponentClass.getTypeParameters().length == 0) {
return rawComponentClass;
}
}
}
return type;
}
}

0 comments on commit 032b52e

Please sign in to comment.