我怎样才能实现这个目标?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
到目前为止我尝试过的所有操作始终返回类型 Object
而不是使用的特定类型。
最佳答案
正如其他人提到的,只有在某些情况下通过反射才有可能。
如果您确实需要该类型,这是通常的(类型安全)解决方法模式:
public class GenericClass<T> {
private final Class<T> type;
public GenericClass(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
}
关于java - 在运行时获取类的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681648/