简体   繁体   English

使用GWT获取超类中的泛型类型类

[英]Get generic type class in superclass with GWT

I have a GWT client generic super-class SuperClass<T> . 我有一个GWT客户端通用超类SuperClass<T> There are sub-classes that explicitly define the generic type, like SubClass extends SuperClass<String> and etc. I need to get generic class type in super-class, something like T.class (of course it doesn't work, but I hope you get the idea). 有一些子类明确定义了泛型类型,例如SubClass extends SuperClass<String>等。我需要在超类中获得泛型类类型,例如T.class (当然不起作用,但是我希望你能明白)。

So I ended up creating a method Class<T> getClassType() in super-class. 因此,我最终在超类中创建了方法Class<T> getClassType() In sub-classes I override it to the following: 在子类中,我将其重写为以下内容:

@Override    
protected Class<String> getClassType(){    
 return String.class;    
}

While it works I don't like this approach as I have to explicitly define the type multiple times. 虽然有效,但我不喜欢这种方法,因为我必须多次明确定义类型。 I'm looking for some workaround so I can write less code is sub-classes. 我正在寻找一些解决方法,以便可以减少子类的代码。

On server-side I could use reflection, but on client side it is unavailable. 在服务器端,我可以使用反射,但是在客户端,它不可用。

I saw some advices on using generators but don't really see how it can help here. 我看到了一些有关使用生成器的建议,但实际上并没有看到它如何提供帮助。

I would pass it through the constructor: 我将其通过构造函数:

public class SuperClass<T> {

    private Class<T> type;

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

    public void Class<T> getClassType() {
        return type;
    }
}

There are third party libraries for this: https://github.com/jhalterman/typetools 有第三方库可用于此: https : //github.com/jhalterman/typetools

There is no other way to get it in the runtime because java generics are a compile time feature. 没有其他方法可以在运行时中获取它,因为java泛型编译时功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM