Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Guava’s TypeToken get the specific type of a generic field?

Tags:

java

guava

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:

TypeToken is similar to Guice's TypeLiteral class, but with one important difference: it supports non-reified types such as T, List<T> or even List<? extends Number>; while TypeLiteral does not. TypeToken is 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());
    }
}
like image 951
yonran Avatar asked Nov 20 '12 00:11

yonran


1 Answers

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
like image 123
Piotr Findeisen Avatar answered Sep 21 '22 15:09

Piotr Findeisen