CHEN1016
V2EX  ›  Java

参数如何传入带泛型的 class

  •  
  •   CHEN1016 · Jun 30, 2023 via iPhone · 2057 views
    This topic created in 1078 days ago, the information mentioned may be changed or developed.
    方法有个参数需要传入一个 class ,但是这个 class 也是带了泛型的,要怎么传入呢
    5 replies    2023-06-30 22:23:34 +08:00
    wolfie
        1
    wolfie  
       Jun 30, 2023
    public static <T, F> void method(Class<T> foo, Class<F> bar) {}
    XiaoXiaoMagician
        2
    XiaoXiaoMagician  
       Jun 30, 2023
    直接贴代码片段或例子把,你的文字没办法呈现出你的具体问题。
    CHEN1016
        3
    CHEN1016  
    OP
       Jun 30, 2023 via iPhone
    @XiaoXiaoMagician <T> ResponseEntity<T>
    exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String,?> uriVariables)比如这个 resttemplate 的一个方法,responseType 要传一个 class ,但是我想返回的类是带泛型的
    mmdsun
        4
    mmdsun  
       Jun 30, 2023 via iPhone
    你发的代码是 Spring 的?是不是这种? ParameterizedTypeReference 是 Spring 的类,处理泛型擦除的

    ResponseEntity<List<MyClass>> responseEntity = restTemplate.exchange(
    url,
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<MyClass>>() {}
    );
    List<MyClass> myObjects = responseEntity.getBody();
    x77
        5
    x77  
       Jun 30, 2023
    参数类型用 Object ,自己写代码转类型,Java 泛型功能不完善,不能依赖它的泛型检查。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3312 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 532ms · UTC 10:36 · PVG 18:36 · LAX 03:36 · JFK 06:36
    ♥ Do have faith in what you're doing.