【问题标题】:How can I define in JAVA generic type that extends Map object with 2 generic parameters?如何在 JAVA 泛型类型中定义使用 2 个泛型参数扩展 Map 对象?
【发布时间】:2023-04-07 04:46:01
【问题描述】:

这是我的代码:

public class Configuration <T extends Map<K,V>, K, V> {
    public Map<K, V> fields;

    public Configuration() {
        this.fields = new T<K, V>(); // --> error: Type 'T' does not have type parameters
    }
}

为什么我不能用泛型参数定义泛型对象?

【问题讨论】:

    标签: java generics map


    【解决方案1】:

    由于 Java 中泛型的设计方式(泛型信息仅在编译时使用),您永远不能使用 new T() 其中T 是类型参数。

    一种可能的替代方法是这样做:

    public interface ConfigurationMapFactory<K, V> {
        public Map<K, V> createMap();
    }
    
    public class Configuration <K, V> {
        public Map<K, V> fields;
    
        public Configuration(ConfigurationMapFactory<K, V> mapFactory) {
            this.fields = mapFactory.createMap();
        }
    }
    

    虽然在这种情况下您可以轻松地做到这一点 - 是否有原因这不起作用?

    public class Configuration <K, V> {
        public Map<K, V> fields;
    
        public Configuration(Map<K, V> fields) {
            this.fields = fields;
        }
    }
    

    【讨论】:

    • 除了句子 you can never do new T() where T is a variable - 你无法知道(编译器也是如此!)类型是否是否定义该构造函数。假设T在运行时是A类型,可能只定义了构造函数A(String str),那么new T()就无效了。
    • 在某些其他语言 (C++) 中,new T() 将是有效的,除非您实际尝试创建 Configuration&lt;SomethingWithoutANoArgsConstructor&gt;
    • 我不知道。但我怀疑更容易出错。
    • 好的,你的答案很清楚,但是没有像 "where T : new()" 这样的约束?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多