如何在Java中创建泛型类的实例?
我的代码有一个大问题,我无法创建通用类的实例 🙁 我的目标是一个服务器,可以处理不同类型的客户端套接字。
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”是一个带有定义构造函数的抽象类。
解决方案:
//... 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
回答
你没有,new像这样的实例是各种设计难题的根源。相反,将 a 传递Function<Socket, T>给班级,并有newClient()call clientCreator.apply(clientSocket)。如果实现就像创建一个新实例一样简单,则只需通过ClientSocketHttp::new.
- Given the OP's code, it looks like they want a `Function<Socket, T>`, not a `Supplier<T>`.