I wrote a parser for a file format called ASN.1 that uses Guice’s TypeLiteral.getFieldType(Field) to convert generic fields into specific Java types so I can construct the correct type (similar to Jackson or GSON databinding). But since I already depend on Guava and it seems to have a new TypeLiteral replacement, I’d like to use TypeToken instead. According to the Guave TypeToken documentation:
TypeTokenis similar to Guice'sTypeLiteralclass, but with one important difference: it supports non-reified types such asT,List<T>or evenList<? extends Number>; whileTypeLiteraldoes not.TypeTokenis also serializable and offers numerous additional utility methods.
Can you get the reified type of a field using TypeToken? In other words, how can I do the following in Guava?
import org.junit.Test;
import com.google.inject.TypeLiteral;
public class FieldTypeTest {
public static class A<T> {
T a;
}
public static class B {
A<String> b;
}
@Test
public void testTypeToken() throws SecurityException, NoSuchFieldException {
TypeLiteral<?> reifiedA = TypeLiteral.get(B.class).getFieldType(B.class.getDeclaredField("b"));
assertEquals(String.class, reifiedA.getFieldType(reifiedA.getRawType().getDeclaredField("a")).getRawType());
}
}
From my head, not verified
Type t = B.class.getDeclaredField("b").getGenericType();
Class<?> p = TypeToken.of(t).resolve(
/* T */ A.getTypeParameters()[0]).getRawType();
// p should be String.class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With