gpt4 book ai didi

java - 如何创建已知类型 : Class> 的类文字

转载 作者:IT老高 更新时间:2023-10-28 20:25:24 25 4
gpt4 key购买 nike

采取以下措施:

public Class<List<String>> getObjectType() {
// what can I return here?
}

我可以从这个方法返回什么类文字表达式来满足泛型并编译? List.class不会编译,List.<String>class 也不会.

如果您想知道“为什么”,我正在编写 Spring 的 FactoryBean<List<String>> 的实现。 ,这需要我实现 Class<List<String>> getObjectType() .但是,这不是 Spring 问题。

编辑: SpringSource 的权力已经听到了我的哀求,因此 Spring 3.0.1 的返回类型将是 getObjectType()改为Class<?> ,巧妙地避免了这个问题。

最佳答案

你总是可以转换到你需要的东西,像这样

return (Class<List<String>>) new ArrayList<String>().getClass();

return (Class<List<String>>) Collections.<String>emptyList().getClass();

但我认为这不是你所追求的。好吧,它有效,但有警告,但它并不完全“漂亮”。

我刚刚发现了这个

Why is there no class literal for wildcard parameterized types?

Because a wildcard parameterized type has no exact runtime type representation.

所以类型转换可能是唯一的方法。

关于java - 如何创建已知类型 : Class<List<String>> 的类文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com