简体   繁体   中英

Is there a way to use GWT.create(…) to instantiate a class of a generic type?

Is there a way I can do something like this:

public class Foo<Bar> {
    public Bar newBar() {
        return GWT.create( /* something useful here */ );
    }
}

Would this work, for example:

public class Foo<Bar> {
    public Bar newBar(Class<Bar> prototype) {
        return GWT.create(prototype);
    }
}

where I would for example do new Foo<MyBar>().newBar(MyBar.class) ?

But, ideally, I wouldn't even need to pass the prototype object.

In this case, no. The GWT.create method must always be called with an actual class literal, never with a variable/field/parameter. This is because GWT.create is actually a special sort of new with no arguments, and that won't work with a variable either (without reflection):

Class<? extends Bar> clazz = ...;
Bar instance = new clazz;//nope

The method GWT.create looks like a method call, and in Java it really is, but when you compile to JS, it must turn into a constructor call, following the specific deferred binding rules of the given permutation.

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