美文网首页
01/04/2017

01/04/2017

作者: 阿三小卷卷 | 来源:发表于2017-01-05 11:35 被阅读0次

    今天遇到两个问题,都不知道是什么原因……

    TypeReference读不出<T>

    public interface Handler <I, O>{
      O handle (I input);
    }
    
    public abstract class AbstractHandler<T> implements Handler<Message, Response> {
      @Override
      public Response handler(Message message) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
      // message.getData() returns List<Map<String, Object>>
      // What I am trying to do here is to convert 'List<Map<String, Object>>' to 'List<Client> or List<OtherType>'
        T domainObjects = mapper.readValue(mapper.writeValueAsString(message.getData(), new TypeReference<T>() {});
      // logic to build response
         return response;
      }
    }
    
    public abstract class ClientHandler extends AbstractHandler<List<Client>> {
    }
    
    public class FirstClientHandler extends ClientHandler {
      // logic related to FirstClientHandler
    }
    

    如果这样些的话,在调用FirstClientHandlerhandle时候, TypeReference会在创建新对象的时候拿到T作为它的reference,显然这个T什么都不是,自然不能被jackson转化成功。只是不明白为什么这个T为什么没有从ClientHandler传递过来……

    Paste_Image.png

    但是如果把这部分code放到具体实现里就完全没有问题了。(这我暂时的解决办法)

    public abstract class AbstractHandler implements Handler<Message, Response> {
    }
    
    public abstract class ClientHandler extends AbstractHandler<List<Client>> {
      @Override
      public Response handler(Message message) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
      // Use actual data type instead of 'T'
        List<Client> domainObjects = mapper.readValue(mapper.writeValueAsString(message.getData(), new TypeReference<List<Client>() {});
      // logic to build response
         return response;
      }
    }
    

    所以问题在于我对继承GenericType的理解还是在于这个TypeReference的实现?不想把这段code放在ClientHandler里的原因是我还有别的各种handler都要用同样的逻辑,差别只在于List里的type


    第二个问题大约google就可以了,只是上班的时间没有顾得上……
    用低version的java跑高version的java compile出来的code会有问题吗?
    Here is the answer from stackOverFlow

    Short answer is yes, but in some cases (with new features that old version doesn't have), then no.

    以上。

    相关文章

      网友评论

          本文标题:01/04/2017

          本文链接:https://www.haomeiwen.com/subject/pgtzvttx.html