Skip to content

Commit

Permalink
Merge pull request #252 from HelloOO7/2.18
Browse files Browse the repository at this point in the history
android-record: Adapt generic types returned by Android reflection to follow Java behavior
  • Loading branch information
cowtowncoder authored Sep 4, 2024
2 parents 862ff03 + fb007fd commit f269b35
Showing 1 changed file with 29 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,31 @@ 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) {
Type componentType = fixAndroidGenericType(((GenericArrayType) type).getGenericComponentType());
if (componentType instanceof Class<?>) {
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;
if (parameterizedType.getOwnerType() == null) {
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 f269b35

Please sign in to comment.