简体   繁体   中英

Get generic type class in superclass with GWT

I have a GWT client generic super-class 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).

So I ended up creating a method Class<T> getClassType() in super-class. 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

There is no other way to get it in the runtime because java generics are a compile time feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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