我怎样才能获得Generic参数类 [英] How can i get class of Generic parameter

查看:119
本文介绍了我怎样才能获得Generic参数类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

获取带反射的java中泛型参数的类型

如何获得通用类

如何获得Generic参数类。

How can i get class of Generic parameter.

 public <T extends BeanProxiable> void method(){
    Class claz = T.class
 }

它是错误。为什么?如何解决这个问题?

It's wrong. Why? How to solve this problem?

推荐答案

您可以动态提供类型,但编译器不会自动为您执行此操作。

You can provide the type dynamically, however the compiler doesn't do this for you automagically.

public abstract class LastActionHero<H extends Hero>(){
    protected final Class<H> hClass;
    protected LastActionHero(Class<H> hClass) {
        this.hClass = hClass;
    }
    // use hClass how you like.
}

BTW:这不是动态得到的,但这取决于它是怎样的用来。例如

BTW: It not impossible to get this dynamically, but it depends on how it is used. e.g

public class Arnie extends LastActionHero<MuscleHero> { }

可以确定Arnie.class有一个带有Generic参数MuscleHero的超类。

It is possible to determine that Arnie.class has a super class with a Generic parameter of MuscleHero.

public class Arnie<H extend Hero> extends LastActionHero<H> { }

在这种情况下,超类的泛型参数只是H。

The generic parameter of the super class will be just H in this case.

这篇关于我怎样才能获得Generic参数类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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