Search code examples
javagenericsfactory-pattern

Generic factory class instantiation


If have a TCP/UDP communications factory as such

public enum IoFactory {
  // Singleton
  INSTANCE;

  public <T> Io<T> create(T type, TransportProtocol protocol) {
    ...
    return ...;
  }
}

which creates Io interfaces:

public interface Io<T> {
  public void send(T msg);
  public T receive();
}

however, when I create an instance of Io with

IoFactory factory = IoFactory.INSTANCE;     
Io<TestMessage> u = factory.create(TestMessage.class, TransportProtocol.UDP);

I get a compilation error saying that the correct instantiation should be

Io<Class<TestMessage>> u = factory.create(TestMessage.class, TransportProtocol.UDP);

what's the deal?


Solution

  • create() accepts a T, as a parameter and return Io<T> as return value.

    However, in your code, you send TestMessage.class as a parameter.
    TestMessage.class is of type Class<TestMessage>, and not of type TestMessage (it is the class object, NOT an object of type TestMessage).

    So, the compiler "understands" that T is Class<TestMessage>, and expects Io<Class<TestMessage>> should be the return type from create(), but you then reassign it to u - which is a variable of type Io<TestMessage> - the wrong type.