在运行时获取通用类的类 [英] Get generic type of class at runtime

查看:98
本文介绍了在运行时获取通用类的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class GenericClass< T> 
{
public Type getMyType()
{
//如何返回T的类型?




$ b $ p
$ b

到目前为止我尝试过的所有东西总是返回<$ code> Object 而不是使用的具体类型。



如果您确实需要这种类型,这是一种常用的(类型安全的)解决方法模式:

  public class GenericClass< T> {

private final Class< T>类型;

public GenericClass(Class< T> type){
this.type = type;
}

public Class< T> getMyType(){
return this.type;
}
}


How can I achieve this?

public class GenericClass<T>
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆