CHEN1016
V2EX  ›  Java

参数如何传入带泛型的 class

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

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