简体   繁体   中英

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

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> 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());
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM