The given assertion will fail due to the error
Failed to find the generated JsonAdapter constructor for class GenericType
How do I get the proper type from the reified type T for Moshi?
I could generate ParameterizedType manually with
Types.newParameterizedType(GenericType::class.java, String::class.java)
where GenericType::class.java is given with T:class.java. But I don’t know how to get the String type parameter to generify the approach.
inline fun <reified T : Any> adapter() =
moshi.adapter<T>(type<T>())
inline fun <reified T : Any> type() =
T::class.java
assert(adapter<GenericType<String>>() != null)
Note that the adapter is available for any GenericType<T>, just not for the actual class GenericType::class.java without generic information.
So the following genericType would find an adapter as long as I know about G:
inline fun <reified G : Any> genericType() =
newParameterizedType(GenericType::class.java, G::class.java)
This G is what I'm looking to find in type(), as T::class.java is just GenericType::class.java there.
from Get ParameterizedType from reified generic type for Moshi type adapter
No comments:
Post a Comment