java - 如何创建泛型类型T的实例

时间:2011-10-28 19:55:22

标签: java generics

我正在编写如下服务器

public class Server<T extends RequestHandler> {

    public void start() {

        try{
            this.serverSocket = new ServerSocket(this.port, this.backLog);
        } catch (IOException e) {
            LOGGER.error("Could not listen on port " + this.port, e);
            System.exit(-1);
        }

        while (!stopTheServer) {
            socket = null;
            try {
                socket = serverSocket.accept();
                handleNewConnectionRequest(socket);
            } catch (IOException e) {
                LOGGER.warn("Accept failed at: " + this.port, e);
                e.printStackTrace();
            }
        }

    }

    protected void handleNewConnectionRequest(Socket socket) {
        try {
            executorService.submit(new T(socket));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但是在handleNewConnectionRequest(...)方法中,我无法创建T的实例,因为它实际上不是一个类。此外,我无法使用提及here的方法,因为我想传递socket实例,以便请求处理程序可以在{{1}上获得OutputStreamInputStream }。


我不能像上面那样制作通用服务器,并且有不同的协议处理程序,例如

socket

然后像下面那样使用它们

public class HttpRequestHandler extends RequestHandler {
    ...
}

public class FtpRequestHandler extends RequestHandler {
    ...
}

public class SmtpRequestHandler extends RequestHandler {
    ...
}

5 个答案:

答案 0 :(得分:9)

你需要一个类的实例。通用类型T是不够的。所以你会这样做:

class Server <T extends RequestHandler> {
    Class<T> clazz;
    public Server(Class<T> clazz) {
        this.clazz = clazz;
    }

    private T newRequest() {
        return clazz.newInstance();
    }
}

答案 1 :(得分:5)

也许使不同的Server子类适合各种处理程序类型。一个例子:

public class HttpServer extends Server<HttpRequestHandler> {

    protected HttpRequestHandler wrapSocket(Socket socket) {
        return new HttpRequestHandler(socket);
    }

}

并像这样适应服务器:

public abstract class Server<T extends RequestHandler> {

    protected abstract T wrapSocket(Socket socket);

    protected void handleNewConnectionRequest(Socket socket) {
        try {
            executorService.submit(wrapSocket(socket));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

只是一个想法...

答案 2 :(得分:1)

你没有。这没有意义。在这种情况下,我可能会避免使用泛型。普通的旧接口或抽象类可以完成工作。您可以使用抽象工厂方法创建抽象服务器。

abstract class Server {
    abstract protected RequestHandler newRequest(Socket socket);
    ... same as before
}

答案 3 :(得分:0)

你不能像Java中的泛型一样直接做到这一点。如果使用getClass()获取RequestHandler的实际类对象,则可以使用Reflection。您可以尝试在构造函数中保存项的类,然后编写如下的辅助方法:

Save the class object (in constructor for example):
this.clazz = requestHandler.getClass()

Then create new object of same class:
E instantiate(Class<E> clazz)
{
    return clazz.newInstance();
}

答案 4 :(得分:0)

/* =================|Cassandra to Java Connection|===================== */
package demo_cassandra_connection;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;

public class java_to_cassandra_connection 
{
    public static void main(String[] args) 
    {
        com.datastax.driver.core.Session ses;
        Cluster cluster= 
        Cluster.builder().addContactPoints("54.191.46.102", 
       "54.149.32.12", "54.191.43.254")
        .withPort(9042).withCredentials("cassandra","cassandra").build();
        ses = cluster.connect();
        Session session = (Session) cluster.connect();
        String cqlStatement = "SELECT * FROM testapp.user";
        for (Row row : ((com.datastax.driver.core.Session) 
        session).execute(cqlStatement)) 
        {
            System.out.println(row.toString());
        }

    }
}