[英]Get a Class<Foo<T>> at runtime given generic type inputs
I know there are a lot of questions about similar issues already, but I haven't found one to directly address this one. 我知道已经有很多关于类似问题的问题,但是我还没有找到一个可以直接解决这个问题的问题。
Here is the skeleton of the code I'm trying to implement: 这是我要实现的代码的框架:
class MyObj<T> {
// Internals are unimportant ...
}
private <T> void foo(T arg) {
Class<MyObj<T>> clazz = // What do I write here?
// Here is one thing that works, but is quite ugly:
@SuppressWarnings("unchecked")
clazz = (Class<MyObj<T>>)(new MyObj<T>().getClass())
// ...
// Later, clazz is passed to a constructor of some other class
OtherClass<MyObj<T>> foo = new OtherClass<>(clazz);
}
Question 1: Does anyone have a better suggestion of how to populate clazz
? 问题1:是否有人对如何填充
clazz
有更好的建议? Ideally, it would avoid calling new
. 理想情况下,它将避免调用
new
。
Question 2: Given the ugly (but working) code above, are there any situations where it could break? 问题2:鉴于上面的代码很丑(但可以正常工作),是否有可能会破坏代码? I don't like to
@SuppressWarnings
, and worry about problems I might be hiding. 我不喜欢
@SuppressWarnings
,并担心我可能隐藏的问题。
To avoid instantiating, you can write: 为了避免实例化,您可以编写:
Class<MyObj<T>> clazz = (Class) MyObj.class;
Due to erasure, there exists a single Class
instance for MyObj
, regardless of whatever type parameters it might have, so although this is ugly, it is safe. 由于删除,无论
MyObj
可能具有什么类型参数,它都存在一个Class
实例,因此尽管这很丑陋,但是很安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.