方法返回对象,而不是在泛型方法

时间:2017-03-22 15:46:43

标签: java generics

我试图了解java的泛型。似乎很难实现我想要的东西。

我想制作一个通用的任务聚合器。意思是,给定一个请求列表,我需要通过一些处理程序(根据请求从工厂获得)处理每个请求。并返回响应列表。现在为了加快这个过程,我希望通过并行执行处理程序来获得结果。

首先,我定义了一个界面THandler

interface THandler<Request, Response> {
        Response handle(Request request);
}

这是我的聚合器:

public class AggTasks
{
    public static <Request, Response> long aggregate(List <Request> req, List <Response> res) {

        CountDownLatch allDone = new CountDownLatch(req.size());
        List <TWork<Request, Response>> workers = new ArrayList<>();
        for (Request r : req) {
            // Getting error: The constructor TWork<Request,Response>(THandler<Request,Object>, Request, CountDownLatch) is undefined
            workers.add(new TWork<Request, Response>(getHandler(r), r, allDone));
        }

        for (TWork<Request, Response> w : workers) {
            new Thread(w).start();
        }
        allDone.await();
        for (TWork<Request, Response> w : workers) {
            res.add(w.collectResponse());
        }

        return 0;
    }
}

这是我的TWork

class TWork<Request, Response> implements Runnable{

        private THandler<Request, Response> handler;
        private Request request;
        private Response response;

        public TWork(THandler<Request, Response> tHandler, Request r, CountDownLatch allDone)
        {
            this.handler = tHandler;
            this.request = r;
        }

        public Response collectResponse() {
            return response;
        }

        @Override
        public void run()
        {
            response = handler.handle(request);
        }

    }

最后这里是getHandler()FactoryHandler。我尝试将返回值明确地转换为THandler<Request, Response>,但是,在编译时它仍然显示为THandler<Request,Object>

    @SuppressWarnings("unchecked")
    private static <Request, Response> THandler<Request, Response> getHandler(Request req) {
        return (THandler<Request, Response>) FactoryHandler.getHandler(req);
    }

    class FactoryHandler {

        @SuppressWarnings("unchecked")
        public static <Request, Response> THandler<Request, Response> getHandler(Request req) {
            return (THandler<Request, Response>) new StringHandler();
        }
    }

欢迎任何改进设计的建议。

修改
我尝试了Wietlol的建议:如果我跳过调用static方法getHandler(),它似乎有效:

workers.add(new TWork<Request, Response>(FactoryHandler.<Request, Response>getHandler(r), r, allDone));

1 个答案:

答案 0 :(得分:2)

FactoryHandler.getHandler(req);

仅定义&#34; Request&#34;的类型,由&#34; req&#34;的类型隐式定义。 响应未定义,因此被预测为Object以使其适用于所有内容。

最简单的解决方案是调用&#34; getHandler()&#34;像这样:

FactoryHandler.<Request, Response>getHandler(req);

明确定义泛型类型。