Java 泛型工厂模式

标签 java generics

我在使用泛型时遇到了工厂模式的问题。我有这个界面,对一切都是通用的:

public interface Connection<T> {
    /* methods */
}

显然,我有这个实现:

public class ImplConnection<V> implements Connection<V> {
    /* body */
}

然后我有这个工厂,它必须创建一个连接实例:

public class ConnectionFactory<V, C extends Connection<V>> {
    private final Class<V> contentType;
    private final Class<C> connectionType;

    public ConnectionFactory(Class<V> contentType, Class<C> connectionType) {
        this.contentType = contentType;
        this.connectionType = connectionType;
    }

    public C newConnection() {
        try {
            return connectionType.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

我正在尝试使用它在运行时实例化连接(我正在使用 Integer 作为通用类型的参数):

connectionFactory = new ConnectionFactory<Integer, Connection<Integer>>(Integer.class, Connection.class);

但是它说:

The constructor ConnectionFactory <Integer,Connection<Integer>>(Class<Integer>, Class<Connection>) is undefined.

最佳答案

传递类参数时,Connection不扩展 Connection<Integer> .所以Class<Connection>不能作为参数提供给 Class<? extends Connection<Integer>> .这就是隐藏在您的错误背后的原因。

如果你想保持这种模式,你应该做的是像这样:

public class IntegerConnection implements Connection<Integer> {}

这会起作用。

但是,一般来说,您知道可以创建通用实例而无需键入任何特殊内容吗?

public class ConnectionFactory {
  public <T> Connection<T> newConnection() {
    return new ConnectionImpl<T>();
  }
}

你可以这样使用它:

Connection<Integer> connection = connectionFactory.newInstance();

关于Java 泛型工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971714/

相关文章:

java - 在整个系统上听鼠标点击(不是在 JFrame 等上)

java - 使用通用通配符代替接口(interface)

java.lang.ArrayIndexOutOfBoundsException 和 If 逗号后面的条目不是整数

c# - 泛型协变转换或转换为实型

go - 有没有一种方法可以使用泛型确保传递的值具有某些字段?

Java、泛型和 PECS : still having trouble understanding the C part; concrete example?

java - 为什么编译时没有任何未经检查的类型警告?

java - @BeforeClass 注释在动态创建的测试套件中不起作用

c# - 如何获取 MIDI 设备的当前状态?

Java G1 GC 处理引用对象运行缓慢