Add java.lang.reflect.Type to TypeRef per #331 (#449)

* Add support deserialization of generic types per #293

* Improving test coverage
This commit is contained in:
Phil Kedy 2021-01-22 18:49:51 -05:00 committed by GitHub
parent 81b47f85b3
commit 38b899d8b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 3 deletions

View File

@ -57,10 +57,10 @@ public abstract class TypeRef<T> {
/**
* Constructor for reflection.
*
* @param clazz Class type to be referenced.
* @param type Type to be referenced.
*/
private TypeRef(Class<T> clazz) {
this.type = clazz;
private TypeRef(Type type) {
this.type = type;
}
/**
@ -118,4 +118,19 @@ public abstract class TypeRef<T> {
return new TypeRef<T>(clazz) {};
}
/**
* Creates a reference to a given class type.
* @param type Type to be referenced.
* @param <T> Type to be referenced.
* @return Class type reference.
*/
public static <T> TypeRef<T> get(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
return get(clazz);
}
return new TypeRef<T>(type) {};
}
}

View File

@ -12,6 +12,7 @@ import org.junit.Test;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@ -234,6 +235,17 @@ public class DefaultObjectSerializerTest {
} catch (IOException exception) {
fail(exception.getMessage());
}
try {
serializedValue = SERIALIZER.serialize(obj);
assertNotNull(serializedValue);
Type t = MyObjectTestToSerialize.class;
TypeRef<MyObjectTestToSerialize> tr = TypeRef.get(t);
MyObjectTestToSerialize deserializedValue = SERIALIZER.deserialize(serializedValue, tr);
assertEquals(obj, deserializedValue);
} catch (IOException exception) {
fail(exception.getMessage());
}
}
@Test
@ -425,6 +437,16 @@ public class DefaultObjectSerializerTest {
} catch (IOException exception) {
fail(exception.getMessage());
}
try {
TypeRef<List<MyObjectTestToSerialize>> tr1 = new TypeRef<List<MyObjectTestToSerialize>>(){};
Type t = tr1.getType();
TypeRef<?> tr = TypeRef.get(t);
result = (List<MyObjectTestToSerialize>) SERIALIZER.deserialize(jsonToDeserialize.getBytes(), tr);
assertEquals("The expected value is different than the actual result", expectedResult, result.get(0));
} catch (IOException exception) {
fail(exception.getMessage());
}
}
@Test