I’m writing a couple of library classes that I am sharing between several projects. Some of these projects are plain-old Java and others are GWT applications. For some of these classes the exact implementation is different whether they need to run in GWT or in Java (Let’s not get into exactly why, but just as one of many examples, Date.getMonth is deprecated in Java, but the Calendar replacement isn’t available in GWT).
Is there a way to mark certain sections of code as pertaining to one or the other scenario?
I looked at using deferred binding and class-replacement in GWT, but that requires instantiation of classes using GWT.create() which isn’t available for a plain-old Java app and will therefore lead to compile errors.
Found a solution that works beautifully: the
<super-source>tag in my library’s .gwt.xml file!Basically, I have two versions of the following EnvironmentFlags class in my library. One in the actual library that is used by Java located in folder “lib“:
my.library.EnvironmentFlags looks like this:
And then a file in the folder “super/my/library” that looks like this:
Now the magic: The .gwt.xml file of my library looks like this:
This leads to plain-old Java using the first version of the EnvironmentFlags class, which simply sets both flags to false, while the GWT compiler replaces the source of that class with the second version loaded from the super-source directory, which sets the GWT flag to true and the DEV_MODE flag to whatever it gets from GWT.
Now, in my code I can simply use the following:
and both, the Java and the GWT compiler should drop the respective unreachable/unneeded code from the compiled result, i.e. no run-time overhead needed.
PS: The IS_DEV_MODE flag doesn’t actually have anything to do with my original question. I just included it as a freebie which allows me to have my code act differently (more verbose, for example) depending on whether I am testing or deploying my GWT app.