Add record getters

This commit is contained in:
Andrea Cavalli 2021-07-13 23:07:18 +02:00
parent 51eaeaae33
commit ff4c803536
1 changed files with 44 additions and 23 deletions

View File

@ -27,8 +27,14 @@ import org.jetbrains.annotations.Nullable;
public abstract class MoshiPolymorphic<OBJ> {
public enum GetterStyle {
FIELDS,
RECORDS_GETTERS,
STANDARD_GETTERS
}
private final boolean instantiateUsingStaticOf;
private final boolean useGetters;
private final GetterStyle getterStyle;
private boolean initialized = false;
private Moshi abstractMoshi;
private final Map<Type, JsonAdapter<OBJ>> abstractClassesSerializers = new ConcurrentHashMap<>();
@ -39,12 +45,12 @@ public abstract class MoshiPolymorphic<OBJ> {
private final Map<String, JsonAdapter<OBJ>> customAdapters = new ConcurrentHashMap<>();
public MoshiPolymorphic() {
this(false, false);
this(false, GetterStyle.FIELDS);
}
public MoshiPolymorphic(boolean instantiateUsingStaticOf, boolean useGetters) {
public MoshiPolymorphic(boolean instantiateUsingStaticOf, GetterStyle getterStyle) {
this.instantiateUsingStaticOf = instantiateUsingStaticOf;
this.useGetters = useGetters;
this.getterStyle = getterStyle;
}
private synchronized void initialize() {
@ -201,25 +207,40 @@ public abstract class MoshiPolymorphic<OBJ> {
for (Field declaredField : this.declaredFields) {
fieldNames[i] = declaredField.getName();
if (useGetters) {
var getterMethod = declaredField
.getDeclaringClass()
.getMethod("get" + StringUtils.capitalize(declaredField.getName()));
fieldGetters[i] = obj -> {
try {
return getterMethod.invoke(obj);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
};
} else {
fieldGetters[i] = t -> {
try {
return declaredField.get(t);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
};
switch (getterStyle) {
case STANDARD_GETTERS:
var getterMethod = declaredField
.getDeclaringClass()
.getMethod("get" + StringUtils.capitalize(declaredField.getName()));
fieldGetters[i] = obj -> {
try {
return getterMethod.invoke(obj);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
};
break;
case RECORDS_GETTERS:
var getterMethod2 = declaredField
.getDeclaringClass()
.getMethod(declaredField.getName());
fieldGetters[i] = obj -> {
try {
return getterMethod2.invoke(obj);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
};
break;
case FIELDS:
fieldGetters[i] = t -> {
try {
return declaredField.get(t);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
};
break;
}
i++;