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

时间:2016-05-11 01:22:19

标签: java generics reflection

如果ElementType是一个静态已知类型,那么它很容易"创建表示Type s:

集合的ElementType对象
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的值。有办法吗?

2 个答案:

答案 0 :(得分:1)

如果你有番石榴,你可以使用他们提供你需要的TypeToken版本:

{{1}}

答案 1 :(得分:0)

根据this post的建议,我最终创建了自己的ParametrizedType实现:

private static class CustomParameterizedType implements ParameterizedType {

    private Type rawType;
    private Type ownerType;
    private Type[] typeArguments;

    private CustomParameterizedType(Type rawType, Type ownerType, Type... typeArguments) {
        this.rawType = rawType;
        this.ownerType = ownerType;
        this.typeArguments = typeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return typeArguments;
    }

    @Override
    public Type getRawType() {
        return rawType;
    }

    @Override
    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CustomParameterizedType that = (CustomParameterizedType) o;
        return Objects.equals(rawType, that.rawType) &&
                Objects.equals(ownerType, that.ownerType) &&
                Arrays.equals(typeArguments, that.typeArguments);
    }

    @Override
    public int hashCode() {
        return Objects.hash(rawType, ownerType, typeArguments);
    }
}

然后我可以这样使用它:

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