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

落爺英雄遲暮 提交于 2020-12-29 11:59:29

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/13464975/can-guava-s-typetoken-get-the-specific-type-of-a-generic-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!