Alwin Brauns
Alwin Brauns

Reputation: 159

How to create an instance of a generic class in Java?

I have this big problem on my code that I can't create an instance of my generic class :( My goal was a server, that can handle different kinds of Client-Sockets.

public class Server<T extends AClientSocket> implements Runnable{
//... some other code
private void newClient() throws Exception
{
    System.out.println("[SERVER] Auf neuen Client warten...");
    Socket clientSocket = serverSocket.accept();
    clients.add(new T(clientSocket)); //Compile Error :(
    new Thread((clients.get(clients.size()-1))).start();
}
//... some more code
public static void main(String[] args) throws Exception
{
    Server<ClientSocketHTTP> server = new Server<ClientSocketHTTP>(8000);
    //... different code
}
}

"AClientSocket" is an abstract class with a defined constructor.

The Solution:

//... some code
private final Function<Socket, T> clientCreator;
public Server(int port, Function<Socket, T> clientCreator) throws Exception
{
    PORT = port;
    serverSocket = new ServerSocket(PORT);
    sockets = new ArrayList<T>();
    this.clientCreator = clientCreator;
}
//... some code
private void newClient() throws Exception
{
    System.out.println("[SERVER] Auf neuen Client warten...");
    Socket clientSocket = serverSocket.accept();
    System.out.println("[SERVER] Client gefunden...");
    sockets.add(clientCreator.apply(clientSocket));
    new Thread((sockets.get(sockets.size()-1))).start();
    System.out.println("[SERVER] Client hinzugefügt...");
}
//... some code
public static void main(String[] args) throws Exception
{
    Server<ClientSocketHTTP> server = new Server<ClientSocketHTTP>(8000, clientSocket -> {
        try {
            return new ClientSocketHTTP(clientSocket);
        } catch (Exception e1) {
            System.exit(0);
            return null;
        }
    });
//... code

Upvotes: 0

Views: 121

Answers (1)

You don't, and newing up instances like this is the source of all sorts of design headaches. Instead, pass a Function<Socket, T> to the class, and have newClient() call clientCreator.apply(clientSocket). If the implementation is as simple as creating a new instance, you can just pass ClientSocketHttp::new.

Upvotes: 6

Related Questions