在运行时获取类的泛型类型 [英] Get generic type of class at runtime
本文介绍了在运行时获取类的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能做到这一点?
How can I achieve this?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
到目前为止我所尝试的一切总是返回类型 Object
而不是使用的特定类型.
Everything I have tried so far always returns type Object
rather than the specific type used.
推荐答案
正如其他人提到的,只有在某些情况下才能通过反射来实现.
As others mentioned, it's only possible via reflection in certain circumstances.
如果你真的需要类型,这是通常的(类型安全的)解决方法:
If you really need the type, this is the usual (type-safe) workaround pattern:
public class GenericClass<T> {
private final Class<T> type;
public GenericClass(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
}
这篇关于在运行时获取类的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文