can I use Class.forName and newInstance in GWT ?

1,556 views
Skip to first unread message

metalhammer29a

unread,
Dec 30, 2010, 1:33:08 AM12/30/10
to Google Web Toolkit
can I use Class.forName and newInstance in GWT ?


static Employee create (String name) {
try {
return (Employee) Class.forName(name).newInstance();
} catch (Exception e) {
throw new IllegalArgumentException ("Unable to instantiate"
+ name);
}
}

Didier Durand

unread,
Dec 30, 2010, 3:11:32 AM12/30/10
to Google Web Toolkit
Hi,

You can't: if you go to http://code.google.com/webtoolkit/doc/latest/RefJreEmulation.html#Package_java_lang
for Class, you will see that forName() is not emulated by GWT.

regards

didier

Danny Goovaerts

unread,
Dec 30, 2010, 3:41:56 AM12/30/10
to Google Web Toolkit
No, you cannot.

Dynamically instantiating classes would invalidate some of the goals
of the GWT compiler.
The GWT compiler builds a javascript application that only contains
code for the actual call graph of your application.
If you would be able to instantiante classes from arbitray Strings, it
cannot determine the call graph anymore.

This is not really a limitation. You can overcome this by using
factories that create instances of a particular class given its name
using a simple string comparison
and GWT.create(). Of course, you need to know all at development time
all the possible classes that you might need to instantiate. If later
you want to add support
for another class, you need to change the code and rebuild. But in
that situation, you probably need to add additional logic to your app
anyway.
Unless of course your app is completely dynamic, but in that case you
should ask yourself the question if GWT is the technology to use.

Regards,

Danny

On 30 dec, 09:11, Didier Durand <durand.did...@gmail.com> wrote:
> Hi,
>
> You can't: if you go tohttp://code.google.com/webtoolkit/doc/latest/RefJreEmulation.html#Pac...
Reply all
Reply to author
Forward
0 new messages