【问题标题】:Unable to obtain a class object of a generic type without using raw types不使用原始类型无法获取泛型类型的类对象
【发布时间】:2019-01-12 00:32:09
【问题描述】:

考虑以下几点:

public interface Converter<I, O> {
    public Class<I> getInputType();
    public Class<O> getOutputType();
}

如果我实现接口并用非泛型类型填充类型参数,一切都很好:

public class ConverterImpl implements Converter<UUID, String> {
    public Class<UUID> getInputType() {
        return UUID.class;
    }
    public Class<String> getOutputType() {
        return String.class;
    }
}

但是,如果我实现接口并用泛型类型填充类型参数,问题就出现了:

public class ConverterImpl<T> implements Converter<Collection<T>, String> {
    public Class<Collection<T>> getInputType() {
        return Collection.class; //Compile time error
    }
    public Class<String> getOutputType() {
        return String.class;
    }
}

因为Collection.class 返回Class&lt;Collection&gt; 而不是Class&lt;Collection&lt;Something&gt;&gt;。但是,原始类型只是为了向后兼容而设计的,不建议使用。使用原始类型是这种情况的唯一解决方案吗?

【问题讨论】:

  • 你不应该使用Collection&lt;T extends Something&gt;吗?
  • 问题是getInputType()getOutputType() API 的真正用途是什么。如果不能代表IO 的完整类型(如果它们是不可实现的),那么调用者在运行时获取“类对象”是否有意义?

标签: java class generics collections raw-types


【解决方案1】:

您需要将 Collection.class 转换为 Class&lt;Collection&lt;T&gt;&gt; 。 试试这个:

public Class<Collection<T>> getInputType() {
    return (Class<Collection<T>>) (Class) Collection.class;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多