gpt4 book ai didi

java - 从动态元素类型获取 ParametrizedType 对象

转载 作者:行者123 更新时间:2023-11-30 07:23:27 26 4
gpt4 key购买 nike

如果ElementType是静态已知类型,创建 Type 很“容易”代表 ElementType 集合的对象s:

Type listType = new TypeToken<ObservableList<ElementType>>(){}.getType();

但这在这里是不可能的,因为我的 elementType是一个动态值,仅在运行时知道:

@Override
public ListProperty<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws
JsonParseException {
Type elementType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
Type listType = // ??? create the type representing a ObservableList<elementType>
ObservableList<?> list = context.deserialize(json, listType);
return new SimpleListProperty<>(list);
}

现在我想要listType代表ObservableList<>哪个类型参数应该是 elementType 的值。有没有办法做到这一点?

最佳答案

如果您有 Guava,您可以使用他们的 TypeToken 版本它提供了您所需要的:

static <T> TypeToken<ObservableList<T>> mapToken(TypeToken<T> typeParameter) {
return new TypeToken<ObservableList<T>>() {}.where(new TypeParameter<T>() {}, typeParameter);
}

@Override
public ListProperty<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws
JsonParseException {
Type elementType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
Type listType = mapToken(TypeToken.of(elementType)).getType();
ObservableList<?> list = context.deserialize(json, listType);
return new SimpleListProperty<>(list);
}

关于java - 从动态元素类型获取 ParametrizedType 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37151549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com