问题描述
我为名为ASN.1的文件格式编写了一个解析器,该解析器使用Guice的 TypeLiteral.getFieldType(Field)
将通用字段转换为特定的Java类型,因此我可以构造正确的类型(类似于Jackson或GSON数据绑定).但是,由于我已经依赖Guava了,并且它似乎有了新的TypeLiteral替代品,因此我想改用 TypeToken
.根据 Guave TypeToken文档:
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
获得字段的简化类型吗?换句话说,我该如何在Guava中执行以下操作?
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
这篇关于Guava的TypeToken可以获取通用字段的特定类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!