采取以下措施:
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/59131105/